text:
SDL2: Why is my player's position not updating?
I've just started getting into game development, SDL in particular, so please go easy on me. I'm struggling to understand why my player's position isn't chaning when I press the left arrow button.
main.cpp
#include <iostream>
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"

typedef struct
{
  float x, y;
  SDL_Texture *sprite;
} Player;

int processEvents(SDL_Window *window, Player *player) {
    SDL_Event event;
    int done = 0;
    while(SDL_PollEvent(&event)) {
        switch(event.type) {
            case SDL_WINDOWEVENT_CLOSE: {
                if(window) {
                    SDL_DestroyWindow(window);
                    window = NULL;
                    done = 1;
                }
            }
            break;
            case SDL_QUIT: {
                done = 1;
            }
            break;
        }
    }

    const Uint8 *keyState = SDL_GetKeyboardState(NULL);
    if( keyState[SDL_SCANCODE_LEFT] ) {
      player->x = 120;
    }
    return done;
}

void render(SDL_Renderer *renderer, Player *player) {
    SDL_RenderClear(renderer);

    SDL_Rect playerRect;
    playerRect.x = 0;
    playerRect.y = 0;
    playerRect.w = 32;
    playerRect.h = 32;
    SDL_RenderCopy(renderer, player->sprite, NULL, &playerRect);
    SDL_RenderPresent(renderer);
}

void update(Player *player) {
     player->x += 10;
}

int main( int argc, char *args[] ) {
    SDL_Window* window;
    SDL_Renderer* renderer;
    SDL_Event event;

    Player player;
    player.x = 50;
    player.y = 0;

    SDL_Init(SDL_INIT_EVERYTHING);
    window = SDL_CreateWindow("Dungeon", 100 , 100, 640, 480, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    player.sprite = IMG_LoadTexture(renderer, "assets/player.png");

    int done = 0;
    while( !done ) {
        done = processEvents(window, &player);
        update(&player);
        render(renderer, &player);
    }
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);
    SDL_Quit;
    return 0;
}

Any help would be much appreciated.
Thanks :)

processEvents sets the player's x-position to the same value each frame, instead of incrementing it like update does. Either processEvents or update should handle player movement. Lastly, the dstRect (playerRect) for SDL_RenderCopy needs to use player->x and player->y to position on the window. The dstRect width and height you have are fine, but be aware that if the srcRect (player.sprite) width and height differ from that of the dstRect then SDL_RenderCopy will scale the player.sprite.

Okay, so there are a number of things I want to comment on, however  first of all, in your render function, you are never actually setting the position of the drawn rectangle to the position of the player:
SDL_Rect playerRect;
playerRect.x = player->x;
playerRect.y = player->y;
playerRect.w = player->x + 32;
playerRect.h = player->y + 32;

I can only assume the update function you had was not working either?

If this doesn't work, it may be to do with how the keyboard data is being fetched. I've only personally used the SDL_GetKeyState(..) function.
You can use it in a very similar way, but it definitely works well:
Uint8* keystate = SDL_GetKeyState(0);
if (keystate[SDLK_LEFT]) {
     player->x = 120;
}

As a personal design preference, I would also put the keyboard processing in the update function rather than the processEvents as you are polling the keyboard rather than waiting for incoming keypress events.
(Though there is no difference in doing this, just organisation).

I understand this is a test project, however I feel it would be more productive for you to experiment and learn in a game engine environment rather than jumping straight into C++. I am only making assumptions of your experience from the code you have provided, however speaking from my own personal experience, it can be counter-productive to try and create games in C++ from the get go, simply because you will run into a lot of brick walls if you aren't all that experienced with the language.
From another point of view, other engines can teach you strong skills in design patterns and program structure which do become increasingly important later on.
I would also say that pure SDL is pretty bad for game development. It is a reasonable "raw" rendering setup that is quick and easy to get setup, however is does not really provide many utility functions that aid in game development. I'd recommend SFML over SDL for this sort of thing, especially because it is a little bit more intuitive as well if you are focused on taking the C++ route. (SFML does a good job of abstracting away alot of the complexity)

1 for advice and SFML is pretty great for beginners. Love2D might also be worth a look. It is Lua bound to SDL and theres a few games made with it and its portable to mobile devices.


text:
Can I use a 3d plane for a 2d game?
I am developing a 2d isometric game and I was wondering if I can use a 3d plane for a 2d game.

That's pretty much what a viewport is

What specific obstacle have you encountered that you're trying to overcome?

Nice answers, but i'm still not sure what you're doing. If you're making a game out of 2d tiles/assets, just use unity's 2d mode, it's a shortcut to the "stacked quads with sprites on with an orthographic camera" configuration that people have been using to make 2d games on a 3d pipeline for a very long time now. If you want a 3d game to look like an isometric 2d game, @Theraot's answer is what you want. If you want the 3d camera system to position 2d sprites for you, that system with carefully placed billboard sprites is probably possible, but i imagine it would be hard to do well quickly.

@StarWeaver what do you mean by stacked quads?

Flat square planar meshes -- i think unity has them as a primative? -- that you texture with a tile or sprite (latter typically with transpanency) and move around. Stacked because they typically come in layers to prevent z-fighting and allow for… layering effects. Since an orthographic camera ignores depth you can use the z axis for scene management. Go take a look at an intro to 2d mode in unity, it's capable and i might be crazy :3

@StarWeaver you mean like instantiating 2d tiles?

Sure, you want an orthographic projection.
Aside from that, you can render using an isometric point of view. That will allow you to look at surface with square tiles and have them appear as isometric tiles. Also, should allow you to use 3D models in your isometric game without worrying about the projection.
The following is from the Wikipedia link above:

There are eight different orientations to obtain an isometric view, depending into which octant the viewer looks. The isometric transform from a point ax,y,z in 3D space to a point bx,y in 2D space looking into the first octant can be written mathematically with rotation matrices as:

where α = arcsin(tan 30°) ≈ 35.264° and β = 45°. As explained above, this is a rotation around the vertical (here y) axis by β, followed by a rotation around the horizontal (here x) axis by α.
(...)
The other 7 possibilities are obtained by either rotating to the opposite sides or not, and then inverting the view direction or not.

Emphasis mine.
Notice the article says there 8 possible such matrices. Some testing will be required to make sure you are use the right one for the coordinates of your map.

For unity, you want to set an orthographic matrix in Camera.projectionMatrix and the isometric matrix shown above in Camera.worldToCameraMatrix.
Note: I don't really have experience with Unity. So I can't tell if Camera.orthographic is a better option than setting an orthograpic matrix to Camera.projectionMatrix.
If you need to set the camera by hand, use the angles shown above (α = arcsin(tan 30°) ≈ 35.264° and β = 45°):

Your assumption is true. You can use Camera.orthographic to enable orthographic projection (true) or perspective projection (false). This can also be done via the Unity Inspector and is set to orthographic by default when 2D projects are created.

@Suddoha I know it can be done, documentation says so. I don't know if it is better.

Yes.
A plane is a flat, two-dimensional surface...
There are infinite planes in 3d space...
You can use any of them...

https://docs.unity3d.com/ScriptReference/Camera-orthographic.html
You want to be in orthographic view.
I found a script that tweens between orthographic and perspective views. I can post it if you'd like?

source: Stack Exchange

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

sort: votes


text:
What kind of ESRB rating do you get for IMPLIED sex?
My game is a story-driven horror game with lots of gore. Obviously, being a horror game places it on the higher end of the age rating already, but because of how backwards the rating system is (female nipples = BAAAAAD!!! Some guy getting his head split in two = eh... who cares) I'm kinda worried that I would get an even higher rating for the sexual themes.
No nudity is ever shown. Some of the characters mostly flirt and say dirty things, not dancing around the f-word (like I just did), and they don't really hold back on the cursing either, but the "worst" you can see is a couple naked in bed after they've done their deed. The actual deed is never shown and you don't see them naked.
Just to be clear, the sexual themes are not the focus of the game, in fact it only happens sparsely. It's mostly about the survival of the main characters.
What kind of rating would my game get?

https://www.esrb.org/ratings/ratings_guide.aspx That would be Mature content but not adults-only.

@ArcaneEngineer You do realize America is not the worst in terms of age rating, right? I specifically didn't mention any countries so everyone could benefit from the answers. (fun fact: I don't even live in the US :D )

If you are referring to ESRB, then we can edit your question to make that clear in the title. EDIT: I have now done so.

@ArcaneEngineer I wasn't referring to any specific rating group - I worded the question so the answer can be of use for people everywhere. America can't be the only one with this backwardness, after all. (Also, why did you remove your comment? Makes my own comment earlier look out of place.)

Q. Without a rating system, how can you get an accurate answer? A. You can't, since different rating systems would have different specifications on how they rank. Until you name a rating system, I will leave "ESRB" in the question title. Otherwise, this question is effectively useless.

@ArcaneEngineer A. You can. By giving an answer on each rating system, like here. That was the point of me not mentioning specific rating systems. If you insist so much on me asking for a specific rating system (for whatever reason), then fine, leave it with the ESRB.

According to the ESRB ratings guide (emphasis mine):

TEEN
Content is generally suitable for ages 13 and up. May contain violence, suggestive themes, crude humor, minimal blood, simulated gambling and/or infrequent use of strong language.
MATURE
Content is generally suitable for ages 17 and up. May contain intense violence, blood and gore, sexual content and/or strong language.

From your description, it sounds like your sexual aspects are merely suggestive, falling under the Teen category. For your suggestive wording and f-word usage, this would probably fall under Teen or Mature depending on how strongly the board feels about it.
All in all, you would have to get your game rated to find out, as every game is different.

If your game is only going to be distributed digitally and you publish using one of the International Age Rating Coalition's  participating storefronts (eg Google Play), when publishing your game, the storefront will let you fill out the IARC's questionnaire to obtain an IARC certificate, which will give you an ESRB rating automatically based on the answers you provide.
Further reading: Microsoft has written a blog post giving insight into how their IARC age rating questionnaire is filled out.

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


text:
Is it legal to copy stats and abilities of characters from another game?
Is it legal to copy stats and abilities of characters from another game?.Please note that my game does have a similar gameplay to the game I am copying. My characters will look different of course.

Please note that "Not being illegal to do so" does not mean "You won't get sued for it".

If I recall correctly, I think the copying of prices and hierarchies from Triple Town was one of the details cited in an infringement case against Yeti Town, which ultimately resulted in a settlement where Yeti Town's copyright was transferred to Triple Town's developer. Basically, every similarly your game has can be one more point of ammunition against you in an infringement case. Better to make your own original games than chance a costly lawsuit.

I am not a lawyer so keep in mind that what I will write is just what I remember from different articles I've read before.
In short:
If you copy only the gameplay part (stat and way of playing) and nothing else, then it should be ok (I repeat double check that. I am not a lawyer)
More details:
If I remember well, in the law point of view, video games are not considered as a whole, but as many parts (music, design, art, animation, etc.) and each part is protected by its own law. The only thing that cannot be copyrighted is the gameplay which include abilities and stats. That's why there is a lot of game being part of the same style of gameplay without problem. But keep in mind that many other details can be protected. For example I think that the name of the ability and the animation when using it can be copyrighted.
Hope it will help you but wait for the answer of someone who truly know the law because I am just repeating things I've heard.

Some links which give you much more details  : http://newmediarights.org/guide/legal/Video_Games_law_Copyright_Trademark_Intellectual_Property#What%20parts%20of%20the%20video%20game%20are%20copyrightable?
http://www.gbgames.com/articles/indie-legal-copyright-and-trademark/what-an-indie-needs-to-know-about-copyright/

@user98577 You're welcome ;) and gl for making your game !


text:
Tips on a Turn Based Strategy AI
I have been working on a game for a while now, and it is going to be a TBS(Turn based strategy) in space.
And now I have come to the point where I am creating an AI for the game. I have no experience when it comes to designing AI's, the first one I ever made was based on random int's and getting the target out of an array.(not exactly a real AI)
On this topic I have a few questions:

How can an AI assess what is the best move to do next? Several units can move every turn.
How does a common AI consider what to do?(Example: Civilization, StarDrive 2, and similar)
How do I manage all the possible outcomes and the moves the AI can/should do?

This question is extremely broad right now, and might not be answerable in a concise way. I think your best bet is to start by doing some research - maybe try a free online course on AI to cover the basics like graph search and minimax strategies, or look up presentations and GDC talks about how existing games have approached AI. This basic research will help you identify techniques you might want to try, and you can then ask more focused questions about implementing them.

Hm, I already used my close vote to mark this question as "Too Broad," but Candid Moon raises a good point below that it may be more appropriate to close this question as a duplicate of "Complex Game AI for Turn-Based Strategy Games"

For the tactical AI of our turn based strategy game we use an approach inspired by utility-based decision making. Here is a simplified explanation:
Each AI Action (i.e. Attack, Advance, Hide) has a list of Considerations and an Execute routine.
Each Consideration is a relatively simple function that takes some parameters (i.e. the tested position, the unit that is tested, etc.) and returns a normalized floating point score (from zero to one). Some example Considerations are ConsiderDamage, ConsiderAnyTargets, ConsiderAdvanceImprovement, ConsiderUnitsSpread, ConsiderSafePath, ConsiderSafeSpot etc.
The AI evaluates all possible Actions at all available positions (i.e. in movement range) by invoking all Considerations for each Action/Position pair, and combining Consideration results by multiplying them. This product is the score for the Action/Position pair.
A boost can be applied to pair scores by multiplication, so some actions are preferred to others. For example in our game the MoveThenAttack action has a boost value a few times higher than the Roam and Advance actions, so MoveThenAttack is almost always preferred by the AI if there is an opportunity for an actual attack at a given position.
Finally the AI picks the Action/Position with the highest score and invokes the Action's Execute routine at Position.
Here are some talks on utility-based game AI:
http://www.gdcvault.com/play/1021848/Building-a-Better-Centaur-AI
http://gdcvault.com/play/1012410/Improving-AI-Decision-Modeling-Through
http://www.gdcvault.com/play/1018040/Architecture-Tricks-Managing-Behaviors-in

You have many options:
1) State machine based on global values, preferences, and location.
2) Machine learning and neural networks.
3) Decision tree.
4) Value map (every tile has its value).
5) Different AI layers that calculate their own behavior, some layers can depend one on another.
6) Combine them all.
7)....
I recommend you watching GDC AI as was stated above in the comments. - this will help you not only create the AI that will beat everyone in the game but to create a real AI that is fun to play against and that you can relax playing vs him - then player won't be tired of the game. And ofc try to make the AI as smart as it can be at the moment and make it more stupid from there if he is easy to beat, but it's only when you have AI - by that I mean don't try to make it super smart in the beginning. I recommend first watching this talk Less is More: Designing Awesome AI for Games - in my opinion, it's the best talk about AI I have ever seen.
Also, this question might be a duplicate of this: AI
EDIT:
(If you haven't already)
I recommend you to learn some Algorithms and Data structures before diving into AI. Understand big O() notation and use the most efficient way to implement AI. Good AI should work fast as well, especially if it's TBS, it will take forever to calculate the things if you did something not efficiently.
Also, learn OOP, programming patterns and code design (architecture). AI without them would be hard to handle.

For future reference, if you think a question is a duplicate of an existing question, or might be too broad to answer completely, it's generally best not to answer it. If there's content you feel is missing from the potential dupe, add your answer on the original question's page - this keeps the information more centralized for future users looking for answers, so they don't need to cross-reference several pages to see the whole story.

Well, actually I can remove the statement about the duplicate, but still, leave the link. Why would I say it's not a duplicate because here OP is asking for tips about AI and AI in TBS. But another answer is asking about the exact AI that was implemented in Civilization V. So this is not a duplicate - that is why I said "might". I didn't think it was a duplicate - I made a guess. Though my question doesn't really answer OP listed questions, but I'm going to change that.


text:
Component super class?
I have recently been programming an Entity Component System in Java for a small game that I am working on. From what I have tested, it works rather well however I question the component part. I currently have an Entity class that stores subclasses of  Component in a HashMap which can be accessed by a String:
private Map<String, Component> components = new HashMap<String, Component>();

The problem is that my root Component class looks like this:
public class Component {

}

I feel as if I've headed in the wrong direction so my question is do I need a Component super class? If so, is there anything that needs to be put in it? If not, should I have a HashMap of Objects instead? Are there advantages to either methods?

Your component base-class seems to be empty now, but it's just a question of time until you will find functionality to add to it. A good candidate might be an update() function which you likely want to have on almost any kind of component.
In the meantime you might want to change it to an interface. That would make it a pure marker interface: An interface which defines no functionality, but marks classes which fulfill some specific purpose or implement some contract, like in your case, being a component.
And by the way: If you want to allow one component per component-type on each entity, you might want to define your hash map as a Map<Class, Component>. You addComponent method would then do this:
public void addComponent(Component newComponent) {
     components.put(newComponent.getClass(), newComponent);
}

GetComponent looks like this:
public Component getComponent(Class type) {
    return components.get(type);
}

and would be called like this:
getComponent(PlayerControllerComponent.class);

This should be a bit faster and gives you the advantage of type-safety (you can no longer misspell your component identification strings).

Wow, thanks for the fast reply and that marker interface concept is pretty much exactly what I need for that class. Also, having a Map that can be accessed with classes that extend Component seems to be a much more secure way of storing components. :)


text:
Loading settings files better?
I have recently been working on a small game project and decided to implement settings loading at game startup. The problem is that my method seems to be too hard coded and not scalable without having a huge method:
public String loadSettings(String path) {
    String[] file = loadFileAsString(path);

    isFullscreen = Boolean.parseBoolean(file[0]);
    windowWidth = Integer.parseInt(file[1]);
    windowHeight = Integer.parseInt(file[2]);
    ...
}

As you can see, this method will get very large after a while and is at risk of crashing if someone edits the file incorrectly so what is a better way of loading this data?

risk of crashing if someone edits the file incorrectly

If the configuration is invalid, then it should not work. You should verify if the data on the file is valid (e.g., It has all the fields, it does not have letters where numbers are expected, etc...) and either notify the user, load default settings or whatever is appropriate for your game.

so what is a better way of loading this data?

If you want the user to be able to edit the configuration file by hand - and you do not want to worry about parsing the file - you should be using some well-known format.
Consider to use INI, JSON, YAML, XML or similar. There are libraries that will handle loading the file for you.
Which one to use is opinion based. You will have to pick considering, for example:

Is there a library available your language and platform?
How hard will it be to edit configuration by hand?
How hard is to handle versioning the settings (e.g. loading a configuration file from an old version of the software that used different fields)?
How fast is to parse the file?
How easy is to validate the data types of the fields?
How resilient is the format to corruption?

Alternatively, any other criteria relevant to your case.
If using a well-known format does not work for you, you could create a proprietary tool to edit the configuration file and use a binary format. It will read faster and will discourage messing with the file directly.

Thanks for the answer, I think that the best method for me would be to load default settings and ask the user if they wanted to reset the settings file. As for parsing, I think using a binary format would be a good idea as it prevents "casual hacking" and Java has the ability to serialise objects anyway.

@Gigas Why are you afraid of people "casually hacking" their config files? A human-readable config file has many advantages. It allows advanced gamers to tweak their config further than your options menu allows and it allows your community to find workarounds for technical problems until you get around patching them (for example when a user managed to screw up their options in a way which prevent them from accessing the options menu). It's also easier for you as a developer, because you have a much easier time experimenting with setting without having to add a UI for them.


text:
Most efficient way to create/modify terrain in real time?
In my game players can modify terrain in real time, but I am not sure what is best practice for this scenario.  I have redesigned and refactored the way the player does this a few times, and am feeling at a loss.
Initially I created small blocks of terrain as GameObjects, but this I quickly realised was grossly inefficient.  Later I devised a system which procedurally generated the 3d mesh by creating vectors and tris for a much larger terrain chunk GameObject, but this is also unfit for purpose.  As I would like the player to be able to place new terrain pieces (replacing old) from premade 3d art assets.
The question is how should one string these pieces together into one map, so that the player can enjoy a large map with a fine level of control?  And for this not to break the game with inefficiency?  Consider that the terrain system is composed of blocks of premade terrain segments, like river or cliff sections.  I feel like I'm missing some basic knowledge of how and when to merge 3d meshes into GameObjects for this purpose?

The answer will entirely depend on the kind of terrain you're trying to generate. What works for one world won't work for another. It's also important how much a player can change the land. Can they remove things? Can they change the height of the land? Clear rocks and trees? Carve caves?

It's unclear to me whether you're asking about assembling completely pre-made blocks of terrain in a tile-based fashion, or stamping of terrain features into a continuous heightmap as was done for the Witcher 3 (see section on stamping workflow in the last 10-15 minutes). Can you add more details or examples of what you want to achieve, and what particular step(s) in the process you need information about?

Heightmap
This is a 2D structure where every value represents either a vertex or a tile between vertices, in a grid structure. Heightmaps have been rendered in every from software scanline renderers (NovaLogic's voxel engine) to modern 3D environments. These were commonly used for rendering 3D in the '80s and '90s due to the low processing cost / simple structure - essentially a 2D array of integer or floating point values. Games like Magic Carpet used this to great effect.
pros: extremely cheap to process and send across network.
cons: Does not allow overhangs, e.g. caves, overhanging cliffs, etc.
Voxels
This is a 3D structure where every value represents one volumetric element in the world (Vo-x-El). As we go from 2 to 3 dimensions, cost increases geometrically (excuse pun).
pros: Much more flexible than the heightmaps from which they evolved, you can really create any space you like (subject to voxel grid resolution / density).
cons: Much more costly to process - optimisation will be a necessity. Also, your terrain will need to be built with different tools, being a voxelised mesh.
Voxel template system
Provided your objects to be placed are static, nothing stops you from querying a voxel space for the placement of say, a 2- or 4- or n-voxel at once. So let's say you have a nice Roman column, maybe it's 5 metres high and your voxel scale is 1m cubed. So you will need 5 voxels vertically to fit this piece in. Query the voxel space in the grid at the player's chosen placement location (on the ground in front of them) and the four above it - place if all 5 spaces are free.
pros Voxels provide a nice neat grid in which to work / place objects. They forego the need for physics since one can use the grid structure and assume they adhere to that (e.g. Minecraft). Collapsing straight down due to gravity is easy enough to accomplish.
cons: Can be costly to check spaces for multi-placement as described above. Your template meshes, e.g. the column, need to be built to fit the underlying voxel system.
Also... Chunks
Chunks are a means of breaking up a large map into smaller, square sections. You only load in certain chunks depending on where the player is currently standing in the world. Each chunk will typically be nxn voxels in depth and width, and m in height (all depends on your coding choices).

The best approach is probably to save the "Pre-made gameobjects" as vertex arrays (x,y,z coordinates) just like you probably would with the terrain mesh. These can be smaller than the array you use to generate the entire terrain. If you find the correct positions in the array you use to generate the terrain mesh by looping through, you can define the position of the "Pre-made gameobject" within the terrain array and adjust the vertex height positions. This should allow the player to click on a location on the mesh and spawn a pre-defined mountain etc...


text:
Unity AssetBundles, server and security concerns
We're trying to implement AssetBundles in our current Unity project for Android and iOS.
My question is about security. To download AssetBundles, our application need to connect to our server. On our server, we got a web service that returns the download link for the bundle needed by the application.
However, the ID and password to connect to our web service are written in plain text in our application. This may sounds as extremely naive, but is this an issue? Could someone find the ID and password from say, the .apk file?
I don't have a lot of knowledge in the field of servers and network security, so I'm trying to keep up with what our team is doing.

Question is, is it harmful if some 3rd party connects to your web service and download some defacto public file? It may and may not be depending on circumstances.

but is this an issue? Could someone find the ID and password from say, the .apk file?

Could be an issue if you don't want people to download those files or you use that ID and password for more important stuff. And yes, people can easily decompile your .apk and find the ID and password.
Anyway, I don't see the need in having to use an ID and password just to download some Asset Bundles, as when it's downloaded onto the user's device they can do whatever they want with it.

One reason I could see for authentication is that lack of authentication allows anyone to download the asset bundle even when they haven't bought the game. Now the question is what value the asset bundle has for anyone without the core game. But that's a question we can't answer.

Exactly. That depends for each game. But the user is going to have those files on his/her device even if you manage to securely lock them behind authentication anyway, so in most cases it's a wasted effort.


text:
GameMaker Android project crashes on IAP
I'm trying to implement a simple IAP in my GameMaker project for Android.
The "store" is a simple room with a button, with this code linked to the "Left mouse button released" event:
if iap_status() == iap_status_available
{
    var product = "donation";
    if ds_map_find_value(global.purchaseMap, product) == 0
    {
        iap_acquire(product, "");
    }
}
else
{
   show_message_async("Store is not available.");
}

and another object with this code linked to the "IAP" event:
var val = ds_map_find_value(iap_data, "type");

switch (val)
{
    case iap_ev_purchase:
        var map = ds_map_create();
        var purchase_id = ds_map_find_value(iap_data, "index");
        iap_purchase_details(purchase_id, map);
        if ds_map_find_value(map, "status") == iap_purchased
        {
            var product_id = ds_map_find_value(map, "product");
            ds_map_replace(global.purchaseMap, product_id, 1);
            switch(product_id)
            {
                case "donation":
                    iap_consume(product_id);
                break;
            }
        }
        ds_map_destroy(map);
    break;

    case iap_ev_consume:
        var product_id = ds_map_find_value(iap_data, "product");
        if ds_map_find_value(iap_data, "consumed")
        {
            ds_map_replace(global.purchaseMap, product_id, 0);

        }
    break;
}

ds_map_secure_save(global.purchaseMap, "iap_data.json");

The IAP is correctly called when the button is pressed, but when the transaction is completed, the game crashes and then crashes at every launch. If I cancel the transaction it doesn't crashes, so I was suspecting the case iap_ev_consume: part to be at fault.
I followed this tutorial: https://help.yoyogames.com/hc/en-us/articles/216755198-In-App-Purchases-Example
Why does my game crashes when an IAP is performed?

What version of GM:S are you currently using? There may be a known bug concerning IAP functions. Also, what's the app store you are developing IAP for? Google Play and Apple Store require slight different settings for purchases to work correctly.

1.4.1763, and I'm on Google Play.


text:
How do I make a launcher for multiple executables?
I'm trying to make a launcher for a game I like that compiles the vanilla version and the mods into one launcher. I want to make it so I can choose between the versions, maybe with a rudimentary GUI. The original versions of the game are in Java, but I'm converting them to .EXE with Launch4j, and that's working fine.

With what are you stuck? Launching an EXE from another program? Making the program per se?

It'd be also nice to know what game you create this for, so we can at least know the background.

This is not about making games but about launching an arbitrary executable that happens to be a game. This would be on-topic on http://stackoverflow.com/ where this question has most likely been answered already.

The game is Minicraft. I checked StackOverflow, it hasn't been answered. :(

I'm stuck on making the launcher. I don't have much experience, and if I really wanted to I guess I could make a Python script, but I wanna make it have MAYBE a rudimentary GUI.

Okay, I just made a BAT file (Batch program, whatever) and coded it like that. I know Batch is a dying language, but I like it and it's fairly backwards-compatible. Here's the code:
@echo off
:beginning
ECHO Minicraft Launcher 1.0
ECHO Coded in Microsoft Batch by Deven Blake
ECHO (C) 2017 Please reproduce with credit to the author.
ECHO.
ECHO    ^>1 Minicraft Vanilla
ECHO    ^>2 Minicraft Flash v1
ECHO    ^>3 Minicraft Flash v2
ECHO    ^>4 Minicraft Flash v3
ECHO    ^>5 Minicraft Flash v4
ECHO    ^>6 Minicraft Plus
ECHO    ^>7 Minicraft Delux
ECHO.
SET /P _inputness= Which Minicraft version would you like to play?
IF "%_inputness%"=="1" GOTO :vanilla-mode
IF "%_inputness%"=="2" GOTO :flashmode-1
IF "%_inputness%"=="3" GOTO :flashmode-2
IF "%_inputness%"=="4" GOTO :flashmode-3
IF "%_inputness%"=="5" GOTO :flashmode-4
IF "%_inputness%"=="6" GOTO :plus-mode
IF "%_inputness%"=="7" GOTO :deluxe-mode
ECHO Option not recognized. Please input a number from one to seven.
GOTO :beginning

:vanilla-mode
minicraft.exe
GOTO :end

:flashmode-1
"minicraft online v1.exe"
GOTO :end

:flashmode-2
"minicraft online v2.exe"
GOTO :end

:flashmode-3
"minicraft online v3.exe"
GOTO :end

:flashmode-4
"minicraft online v4.exe"
GOTO :end

:plus-mode
"minicraft plus.exe"
GOTO :end

:deluxe-mode
"minicraft delux.exe"
GOTO :end

:end

That's not the final edit before I release it on Github (with mention that I didn't create the original games, I only made the launcher), but it's a nice start. Thanks, you guys, for trying to help.
UPDATE: Minicraft Ultimate on GitHub

What makes you think batch is a dying language? It's the built in scripting language for windows.

@Bálint Microsoft is slowly phasing out Batch for PowerShell, which I hate.


text:
GameMaker project works fine when targeting Windows but not when targeting HTML5
As mentionned in the title, my GameMaker project works fine when targeting Windows.
However, when I build it for HTML5, I got those errors in the Chrome developer console:
Destructive Dark.js?VYNZB=1666826811:7 Uncaught TypeError: Cannot read property '_42' of undefined
    at _Qw1._M [as _L] (Destructive Dark.js?VYNZB=1666826811:7)
    at _Qw1._a4 (Destructive Dark.js?VYNZB=1666826811:1490)
    at _a72._a4 (Destructive Dark.js?VYNZB=1666826811:1380)
    at _lK1 (Destructive Dark.js?VYNZB=1666826811:1155)
    at _9v2 (Destructive Dark.js?VYNZB=1666826811:1742)
    at _Mu2 (Destructive Dark.js?VYNZB=1666826811:1748)
    at _Ju2 (Destructive Dark.js?VYNZB=1666826811:1733)

I suppose this error is not really useful since it seems to come from the obfuscated Javascript... However, I noticed that this error appears on the "Left mouse button released" event on one of my object. The code associated with this event is the following:
/// Select the square or switch its place with the current selected square

game_manager = instance_find(obj_game_manager, 1);

if (game_manager.lock_timer == 0) {
    if (game_manager.selected_square == noone) {
        game_manager.selected_square = self;
        inst = instance_create(x, y, obj_selection);
        inst.depth = -100;
        inst.image_alpha = 0.6;
    }
    else if (game_manager.selected_square == self) {
        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }
    }
    else {
        // Lock interactions
        game_manager.lock_timer = 2;

        // Switch the array cells
        var x_temp = game_manager.selected_square.x_grid;
        var y_temp = game_manager.selected_square.y_grid;
        var color_temp = game_manager.selected_square.color;

        game_manager.grid_array[x_temp, y_temp] = color;
        game_manager.grid_array[x_grid, y_grid] = color_temp;

        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }

        with (game_manager) {
            event_perform(ev_alarm, 0);
        }
    }
}

Not much info sorry, but I have no ideas where this error came from.

About code...
Use id instead self:
game_manager.selected_square = id;

Use var for temporary variables:
var inst = instance_create(x, y, obj_selection);
inst.depth = -100;
inst.image_alpha = 0.6;

(of course, if you knowingly use it as object variable, then it's ok)
Or even something like this:
with instance_create(x, y, obj_selection) {
    depth = -100;
    image_alpha = 0.6;
}

Don't use multiple dots without braces:
game_manager.selected_square.x_grid;   // no
(game_manager.selected_square).x_grid; // yes

Other way which can be useful there:
var square = game_manager.selected_square;
...
var x_temp = square.xgrid;
var y_temp = square.ygrid;
var color_temp = square.color;

It's shorter and, as a result, more comfortable for reading.
(But keep in mind, that is usable for reading, but not for change original value, i.e. game_manager.selected_square = noone;, but not square = noone;).
When statement has only one command, you can omit curve braces:
    with (obj_selection) {
        instance_destroy();
    }

    with (obj_selection)
        instance_destroy();

or even
    with obj_selection
        instance_destroy();

(GMS highlights names of objects, so it's ok for reading).
Same for if.
Now about your problem. Possible that problem is here
game_manager.selected_square.x_grid;

but if no, then not very hard to find where is it.
Write to debug console messages in key places of the code and you will know, where the error happens.
For example, firstly you can do it inside each if:
/// Select the square or switch its place with the current selected square

show_debug_message("script 1");

game_manager = instance_find(obj_game_manager, 1);

if (game_manager.lock_timer == 0) {
    show_debug_message("1");
    if (game_manager.selected_square == noone) {
        show_debug_message("2");
        game_manager.selected_square = self;
        inst = instance_create(x, y, obj_selection);
        inst.depth = -100;
        inst.image_alpha = 0.6;
    }
    else if (game_manager.selected_square == self) {
        show_debug_message("3");
        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }
    }
    else {
        show_debug_message("4");
        // Lock interactions
        game_manager.lock_timer = 2;

        // Switch the array cells
        var x_temp = game_manager.selected_square.x_grid;
        var y_temp = game_manager.selected_square.y_grid;
        var color_temp = game_manager.selected_square.color;

        game_manager.grid_array[x_temp, y_temp] = color;
        game_manager.grid_array[x_grid, y_grid] = color_temp;

        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }

        with (game_manager) {
            event_perform(ev_alarm, 0);
        }
    }
}

show_debug_message("script 1 finished");

For example, you found that 4 is last message was printed. Then do same for each line of that block:
else {
    show_debug_message("4");
    // Lock interactions
    game_manager.lock_timer = 2;

    show_debug_message("4-1");

    // Switch the array cells
    var x_temp = game_manager.selected_square.x_grid;
    show_debug_message("4-2");
    var y_temp = game_manager.selected_square.y_grid;
    show_debug_message("4-3");
    var color_temp = game_manager.selected_square.color;

    show_debug_message("4-4");
    game_manager.grid_array[x_temp, y_temp] = color;
    show_debug_message("4-5");
    game_manager.grid_array[x_grid, y_grid] = color_temp;
    show_debug_message("4-6");

    game_manager.selected_square = noone;
    show_debug_message("4-7");

    with (obj_selection) {
        instance_destroy();
    }

    show_debug_message("4-8");

    with (game_manager) {
        event_perform(ev_alarm, 0);
    }
}

And see what message will be last. Next line will be your goal.

Thanks a lot. Turns out the issue was game_manager = instance_find(obj_game_manager, 1); which was supposed to be game_manager = instance_find(obj_game_manager, 0);. I don't know why the first one worked on Windows though.

On Windows instance_find for wrong index returns id of last instance, but on HTML5 it returns noone. I guess the runner has no check of maximum correct index because performance optimizations, so developer must check it manually.


text:
How to design a class for an object that its state varies over time
I have a soccer team with 14 players (11 active + 3 substitutes). The team is going on a tour participating in different matches across the world. I have two very different design ideas of how for the classes for such match, and I am wondering if there is a better approach here. The language is Python and the database is Mongo.
My requirements:

At any time during a match, I want to know the current status of a player. (substitutes, active, injured) as well as their penalty cards if they got any. If they are actively playing, I want to know when they started. If they got back to sitting or got injured, I want to know their most recent start time and end time.
I want to be able to retrieve the information about a past match. For any player in a past match, I only need to know their latest status (as described above)

Here is my idea about db collections:
Players collection:
- Player ID
- Player Name
- Player Tshirt Size

Teams collection:
- Team ID
- Team Player IDs []
- Team Name
- Team logo

Matches collection:
- Match ID
- Team ID
- Match Location
- Match Time

Match Participants collection:
- Player ID
- Match ID
- Latest Status
- Latest Start Time
- Latest End Time
- Latest Penalty Card
- Latest Injury Note

As you see, I tried to separate the static information about a player (Players collection) from their dynamic information in a match (Players History collection) but I not sure how to define classes?
Class Player:
- Player ID
- Player Name
- Player Tshirt Size
- Latest Status
- Latest Start time
- Latest End time
- Latest Penalty Card
- Latest Injury Note

Class Match:
- Match ID
- Player IDs []
- Match Location
- Match Start time
- Match Tshirt color

The second option would be creating another class for the dynamic part to match to my db collection:
Class Player:
- Player ID
- Player Name
- Player Tshirt Size

Class Match:
- Match ID
- Player IDs []
- Match Location
- Match Start time
- Match Tshirt color

Class Match Participant:
- Player ID
- Match ID
- Latest Status
- Latest Start time
- Latest End time
- Latest Penalty Card
- Latest Injury Note

I do not know how I should decide which approach is better. I would appreciate if you help me figure out the approaches pros and cons or even just what criteria I need to think about when deciding between the two.
Is there any design patterns that would describe any of these approaches?

The first point of your requirements describe events that belong to the match itself, you can define a base class for that
Event
- matchId
- time

And construct specific classes based on it: MatchStarted, PlayerInjured, PlayerEnters, PlayerLeaves, PenaltyCardShown, if want to avoid that, you can create classes with a type property (less oop). Each class can contains specific properties for each event, like playerId for example.
Now. using a service or a query class, you can query against the event list to get the status of players or the match at any time. With the time field is easy to get the last one. Also you can have methods like latestPenaltyCard in your match class to get the data more at hand
In that way your model classes gets very clean, just holding the static data
For raising and storing the events you can use event sourcing or something like that
For storing in the database, maybe I would use an event class that contains all the columns for every event type (and the "type" field), for facilitate querying

I do like this solution a lot. But never the less I like to suggest minor improvements, which are: remove the event MatchStarted because it is not motivated by the requirements. Now we are able to add the attribute playerId to the Event class, because all the events we are interested in are associated with a player right? That's it.

@Harmlezz yes, you can do that, it all depends on the requirements.

@HeCtOr  Why do I need to have an events generated when an action happens? Then I will ended up with so many "event" objects in my db, right? As mentioned in the requirement, for the past or a current match, I only need to know the latest information about each of the players (And I do not know when a match finished, just know the start time of a match) So I only needed to keep one record per match per each player.

And besides, I do not need to generate an event when a match starts, because that information is static (I know in advanced when a match supposed to start). If you think I did not get your approach, do you mind explaining more in detail maybe write the classes and their fields? And I appreciate if you could name a design pattern to support your ideas. Especially I separated the db design from my object oriented design, I so much appreciate if you could do the same.


text:
Show the progression of a loop in GameMaker Studio
I'm using a loop to destroy some objects in my code.
for (var i = 0; i < instance_number(obj_item); i++)
{
    var inst = instance_find(obj_item, i);
    with (inst)
        instance_destroy();
}

I would like to make them disappear one at a time on screen (i.e., the first one disappears, one second after that the second one disappears, etc.).
However, it seems that the screen is updated only when the loop has finished: all objects disappear at once.
In Unity, I would use coroutines for such a situation. How do I do that in Gamemaker?

Use alarm for this, like:
if instance_exists(obj_item)
{
    with instance_find(obj_item, 0)
        instance_destroy();

    alarm[0] = room_speed; // one second
}

place this code in alarm 0 and then start it using alarm[0] = 1;


text:
How to render in an entity component system?
I am currently working on a game in Java that uses an entity component system. The game currently has two separate update() and render() methods in the game loop however this does not seem to fit with my entity component system. From what I understand, each system in an ECS has an update method but what about say, a rendering system that draws sprites to the screen? How does rendering work with an ECS? One idea could be to have systems that draw on the screen implement a RenderSystem interface so that they are only used in the rendering method but I've never seen anything like this. Is there a certain way of doing this?

Related question: Should actors in a game be responsible for drawing themselves?

A common way to implement rendering in an ECS is to have a Renderer component on any entity which is supposed to be visible in the game world. This component would hold all the information which is required by the graphic engine (which you can call RenderingSystem if you like) to visualize this entity.

So a system where the render system holds information about entities to be used every render call? Currently the update() method is called 60 times per second and the render() method is called every loop. So could it be possible to store render information in the render system in the update() function to be later used in the render() function in the renderer?

@Gigas Certainly. One thing you could handle in Renderer.update is animation.


text:
Flipping the game so that the local player is always on the left side of the screen?
I'm making a 1v1 game with each player at one end of the screen. The game is an online client-server game. I would like the local player to be on the left side of their screen and their opponent (the remote player)  on the right side. Similar to Clash Royale where the local player is always on the bottom and their enemy always on top.
What is the easiest way for me to accomplish this?
Some solutions I've thought of so far:

The server checks every time it sends data back to the players that if it's sending the data back to player 2, it flips it before sending it back. I don't particularly like this solution because it will greatly complicate the code, increasing the chances of bugs, and make it less flexible / re-usable in the future.
The client checks if it is player 2 and flips the data it received back from the server if it is. I don't like this solution for the same reasons as above.
Some camera tricks I don't know about.

It might be helpful if you gave a short description or an image of your game to help illustrate your issue.

Like in Clash Royale, the local player is always at the bottom of the screen and the player's opponent is always on top. I want to achieve the same thing but instead of top / bottom, left and right.

I found out how to do it.
I used this script from the wiki: http://wiki.unity3d.com/index.php?title=InvertCamerahttp://wiki.unity3d.com/index.php?title=InvertCamera
It's in JS and a bit outdated so here's a revised version:
using UnityEngine;

public sealed class CameraFlipper : MonoBehaviour
{
    private void OnPreCull()
    {
        Camera.current.ResetWorldToCameraMatrix();
        Camera.current.ResetProjectionMatrix();
        Camera.current.projectionMatrix = Camera.current.projectionMatrix*Matrix4x4.Scale(new Vector3(-1, 1, 1));
    }

    private void OnPreRender()
    {
        GL.invertCulling = true;
    }

    private void OnPostRender()
    {
        GL.invertCulling = false;
    }

Now, this will literally flip everything from left to right. Text will become illegible.
To prevent certain objects from being flipped by the camera, put them all in a new layer (ie. "Text Layer") and on the flipped camera's culling mask, unselect "Text Layer". This will make the camera not render any object inside the "Text Layer" layer. To get the text to render properly, create a 2nd camera that is not flipped and set the culling mask to only "Text Layer".
Hope that makes sense.


text:
How to start the game at the same time across two phones?
I am trying to synchronize two devices so that they can start the game at the same time.
The mechanism that I've thought about is that I would use the phones' time and set the intervals at, for example, ten seconds each. Then, when the start button is clicked, it will start the game on the beginning of the next interval. So, as long as the start buttons on both devices are clicked in a short time frame of each other, the game should start at the same time.
For the game, near perfect synchronization is important.
Will this work? I am assuming that every phone receives a timestamp from a single source, so that internal clocks are at the same time.
If that doesn't work, what is an alternative/better solution to offline multi-device synchronization?

What platform are you on? You should not synchronize the two devices with their own time but connect them somehow to each other and send a message to start the game.

Android (android studio), with hopes of making it cross platform.

Use Bluetooth, Nearby, Wifi Direct to connect the devices

Why are those better methods than the one I mentioned? Just curious

I only need them to start at the same time, not be linked in any other way.

It's better because you cannot be sure that the time on two devices is the same. You should never rely on classical time but rather on a queue of commands

The best resource on how to do all kinds of synchronization of advanced physical simulations over unreliable networks in games is the excellent blog posts/articles of Mr. Glenn Fiedler.
You can find it here, and the spesific article you want is here. Search for the topic "Measuring Round Trip Time" in that article.
To summarize (copied verbatim):

For each packet we send, we add an entry to a queue containing the     sequence number of the packet and the time it was sent.
Each time we receive an ack, we look up this entry and note the difference in local time between the time we receive the ack, and the
  time we sent the packet. This is the RTT time for that packet.
Because the arrival of packets varies with network jitter, we need to smooth this value to provide something meaningful, so each time we
  obtain a new RTT we move a percentage of the distance between our
  current RTT    and the packet RTT. 10% seems to work well for me in
  practice. This is called an exponentially smoothed moving average, and
  it has the effect of smoothing out noise in the RTT with a low pass
  filter.
To ensure that the sent queue doesn’t grow forever, we discard packets     once they have exceeded some maximum expected RTT. As
  discussed in the previous section on reliability, it is exceptionally
  likely that any packet not acked within a second was lost, so one
  second is a good value for this maximum RTT.

The delay of an internet network packet is usually < 100 ms. For a single action like you describe, this difference is usually too short to be noticed.
In comparison, the clock in 2 different phones on 2 different operators is rarely more than 2 minutes (120'000 ms) apart, if you account for time zones correctly.
If you can't - or don't want to - use the internet, you could use wifi direct or bluetooth.
If you don't want to use these either: Do your devices have microphones? If you're up for the challenge, you can have a "beep" based activation, where the game starts as soon as the second device hears the first device beep.
A possibly easier solution is to simply have 2 users press the start button at the same time, with audible feedback so they know the other user started at the same time. That way they would be within 200 ms of each other.

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


text:
Multiple Indices Problem
Recently, I've been trying to use COLLADA files in OpenGL. The problem that a lot of people before me have run into is COLLADA's indice structure. It has multiple sets of indices, the first is for position, the second for the normal.
I know by now that it is completely impossible for OpenGL to use multiple sets of indices, so I must rearrange my normals so that I can use my position indices for my normals.
I've already made some code for this, but it doesn't seem to turn out right.
private static Vector3[] RearrangeNormals(Vector3[] norms, Vector3[] pos, int[] posindices, int[] normindices)
{
    Vector3[] newnorms = new Vector3[norms.Length] ;
    for (var i = 0; i < norms.Length; i++)
    {
            newnorms[posindices[i]] = norms[normindices[i]];
    }
    return newnorms;
}

With this function, it seems like half of my Suzanne mesh has it's normals correct, the other half... not so much. Here's an image of what I'm getting with my lighting test.
How should I handle rearranging my normals (or texcoords maybe in the future)?

The pos argument is unused.

You are assuming that the number of normals and number of positions is the same. This may not be true.
If there are more positions than normals, then you are accessing newnorms out of bounds.
Before fixing this you need to make a choice. Do you:

Want to draw non-indexed.
Want to draw indexed.

In case of 1, you simply generate non-indexed data by looking up the norm/pos before feeding it to OpenGL.
In case of 2, you would need to first determine all unique pos+norm values, before you can assign an index to it.
The first option is easier, and would mean using glDrawArrays, not glDrawElements. Some people argue that indexed primitives can be faster, but personally, I have found it not worth the extra effort.

Here's an answer that works for me, although doesn't directly answer the question.
Ready? (Drum roll)
Use .X3D
This format is actually really great. Unlike COLLADA, you can edit the up axis in Blender so that it is exported as Y-Up, it only has one set of indices and all the data for a single mesh is stored in one child (including the materials).
I was actually quite surprised at the fact that not a lot of people are using this, even though it seems like it was made for OpenGL!


text:
Which Type of Collision Detection should I use?
So over the past week I've been scratching my head over SAT (Separating Axis Theorem). I know how it works, but can't seem to get the C# code right. There's always one face or edge that's letting my player through an obstacle.
So I wanted to know if maybe I'm taking the hard way around, and I don't need SAT for what I want to achieve.
My Game Involves:
- 3D Cubes which will sometimes be on an angle (not a multiple of 90)
 - Not too many cubes (so I don't need my Collision Detection to be too inexpensive) - OBB collisions
So what is the best option for me collision-wise? If SAT is my go to option, what would it look like in C#?
EDIT
My Sat code:
var n1 = (bb1.BCK_TOP_LFTCorner - bb1.BCK_BTM_LFTCorner).Normalized();
var n2 = (bb1.BCK_BTM_LFTCorner - bb1.BCK_BTM_RGTCorner).Normalized();
var n3 = (bb1.FRT_BTM_LFTCorner - bb1.BCK_BTM_LFTCorner).Normalized();
var n4 = (bb2.BCK_TOP_LFTCorner - bb2.BCK_BTM_LFTCorner).Normalized();
var n5 = (bb2.BCK_BTM_LFTCorner - bb2.BCK_BTM_RGTCorner).Normalized();
var n6 = (bb2.FRT_BTM_LFTCorner - bb2.BCK_BTM_LFTCorner).Normalized();
var norms = new List<Vector3>() {
     new Vector3(-n1.X, n1.Y,n1.Z),
     new Vector3(n2.X, -n2.Y,n2.Z),
     new Vector3(n3.X, n3.Y,-n3.Z),
     new Vector3(-n4.X, n4.Y,n4.Z),
     new Vector3(n5.X, -n5.Y,n5.Z),
     new Vector3(n6.X, n6.Y,-n6.Z),
};
norms = bb2.Normals;
float max1 = 0;
float min1 = 0;
float max2 = 0;
float min2 = 0;
for (int a = 0; a < norms.Count; ++a)
{
    //Global.Min/Global.Max are simply Math.Min/Math.Max for an array of parameters
    max1 = Global.Max(Vector3.Dot(bb1.Corners[0], norms[a]),
            Vector3.Dot(bb1.Corners[1], norms[a]),
            Vector3.Dot(bb1.Corners[2], norms[a]),
            Vector3.Dot(bb1.Corners[3], norms[a]),
            Vector3.Dot(bb1.Corners[4], norms[a]),
            Vector3.Dot(bb1.Corners[5], norms[a]));
        min1 = Global.Min(Vector3.Dot(bb1.Corners[0], norms[a]),
            Vector3.Dot(bb1.Corners[1], norms[a]),
            Vector3.Dot(bb1.Corners[2], norms[a]),
            Vector3.Dot(bb1.Corners[3], norms[a]),
            Vector3.Dot(bb1.Corners[4], norms[a]),
            Vector3.Dot(bb1.Corners[5], norms[a]));
        max2 = Global.Max(Vector3.Dot(bb2.Corners[0], norms[a]),
            Vector3.Dot(bb2.Corners[1], norms[a]),
            Vector3.Dot(bb2.Corners[2], norms[a]),
            Vector3.Dot(bb2.Corners[3], norms[a]),
            Vector3.Dot(bb2.Corners[4], norms[a]),
            Vector3.Dot(bb2.Corners[5], norms[a]));
        min2 = Global.Min(Vector3.Dot(bb2.Corners[0], norms[a]),
            Vector3.Dot(bb2.Corners[1], norms[a]),
            Vector3.Dot(bb2.Corners[2], norms[a]),
            Vector3.Dot(bb2.Corners[3], norms[a]),
            Vector3.Dot(bb2.Corners[4], norms[a]),
            Vector3.Dot(bb2.Corners[5], norms[a]));

    }
if (max1 < min2)
    return Vector3.Zero;
    // Get nearest face normal to player so that we can add it to player's velocity.
    var rl = new List<Vector3>() {bb2.Front,
        bb2.Back,
        bb2.Top,
        bb2.Bottom,
        bb2.Left,
        bb2.Right };
    var r = rl.IndexOf(rl.OrderBy(c => c.Distance(bb1.Center)).First());
    var returnval = bb2.Normals[r];
    return returnval;

Maybe you should show your code

Okay, I'll make sure to do that when I'm at a computer.

SAT is a good algorithm for learning narrow phase collision detection, as the code is pretty intuitive.
As to what it would look like in language X, you should simply read a tutorial on SAT and then port it to your language of choice once you understand the algorithm completely.
I would say this though: If you plan to do any sort of accurate physics, you will need additional processing on top of SAT code to compute contact points, and online tutorials are a little spotty on that subject.
If you find the additional processing is hard to find/wrap your head around, take a look at:

Gilbert Johnson Keerthi (GJK)
Expanding Polytope Algorithm (EPA)
Minkowski Difference

All these are perhaps a little more difficult to wrap your head around, but they are pretty fast, and provide contact points "out of the box" will no additional processing.

Thanks Ian, a little late to the party, but I'll still research these.


text:
Should I sync animations from the server to the client or let the client play its own animations?
For example, if the user presses the "Fire" button which leads to the player character doing some kind of animation, should the client evaluate itself if it can play the animation or wait for a response from the server telling it that it's ok to play the animation?

If you're going with the authoritative server model (to limit player cheating), you want to simulate everything immediately on the client. Otherwise, there will be latency, so the player could press fire, and 200ms later see the animation, which would be a poor experience.
When the server sends back updates, the client must rewind to the state last processed by the server, then replay any local inputs not yet processed by the server to appear responsive.
See this tutorial series: http://www.gabrielgambetta.com/fpm1.html

Yes I was thinking that but how would you avoid disagreements from the server? Say the Client casts a spell so the cast spell animation is played but the server says the client can't cast the spell because he actually has no mana.

In disagreements, the server always wins. It's up to you on what to display on the client. For instance, you can start playing the animation, then stop if the server denies the cast. Immediately display the aesthetic feedback, but don't deal any damage until the server approves it. One AAA example is in Halo 3, a grenade throw would start the throwing animation, but the grenade wouldn't actually appear until the server verified it.


text:
Can I make my sprite design very similar to Pokémon's sprite design?
I'm making a 2d RPG and I'm having trouble designing a sprite, so I downloaded an image of Pokémon Leaf Green's player sprite and copied how it looked. I didn't copy it completely, only how it looks. Here's the image:

Can I get sued for this? the gameplay and mechanics are far from Pokémon's mechanics, the only problem is the sprite of the characters. Can I get into trouble because the character sprite looks too much like Pokémon's character?

To answer your questions, No, yes, and yes. IANAL, and you should consult with one.

You can get sued for anything. The more interesting question is if you would win a lawsuit if someone decides to sue you. And that depends not just on the legal situation but also on the skill of the lawyer you can afford.


text:
Issue whith transparent textures when loading a prefab in Unity
I'm trying to implement Asset Bundles in my Unity game.
I used to instantiate a prefab with Instantiate<GameObject>(gameRootPrefab), which worked fine.
Now this prefab is in a Asset Bundle, so I'm loading this Asset Bundle with AssetBundle.LoadFromFile(), and get the prefab to instantiate with LoadAsset<GameObject>(prefabName). I instantiate the prefab the same way as before.
However, I'm now getting an issue with some transparent textures:

This white square is supposed to be a texture with some transparent parts.
I tried tweaking the material and the texture associated to this GameObject, but I'm still getting the same result. Here's the material and texture:

Is the material and texture getting loaded (or need to be) from the asset bundle too?

I put a prefab holding a reference to that material into the asset bundle, so yes I guess.

I'm honestly not show how that works, you may have to load the texture separately. Or the material. I don't know. But that's what is looking like is happening.

did you get solution on this i have same problem.

@eswarkumar Given the state of this question, if you end up creating a new question about this, we'll close this one as a duplicate of your own, new question.


text:
Serialize ScriptableObject without creating an asset out of it?
Is it possible to do something like this?
public class SomeScriptable : ScriptableObject
{
    public MyScriptable myScriptable;

    public void OnValidate()
    {
        if (myScriptable == null)
        {
             myScriptable = ScriptableObject.CreateInstance<MyScriptable>();
         }
    }
}

public class MyScriptable : ScriptableObject
{

    public int MyVar1;
    public string MyVar2;

}

I tried this but am getting a "Type Mismatch" error in Unity.

Can you clarify, are you trying to create a ScriptableObject, like your code seems to try to do, or serialize one, as the current title describes?  (ie. convert a ScriptableObject to a sequential representation to write to a file or send over a network) If the latter, what do you want to serialize it into, if not an asset file? ScriptableObjects are generally thorny to serialize outside of Unity's editor functionality, so if you're headed that way it might be worth telling us more about your application - there may be simpler solutions to the root problem.

@DMGregory I am trying to serialize a ScriptableObject at design time without creating an asset for it. I'll have a custom inspector and the user will be able to select from certain ScriptableObjects that inherit from a certain type in the loaded assemblies. I want it to serialize as part of the Monobehaviour / ScriptableObject it's in, just like if it were a regular [Serializable] class.

It's odd, as it is now, you should get a CS0103 compiler error, due to the fact that you need to write:
myScriptable = ScriptableObject.CreateInstance<MyScriptable>();

Moreover, if the MyScriptable class it's inside the MyComponent script attached to a game object, you'll get a warning - to get rid of it you need to cut the MyScriptable class code from it and put it in its specific script, named ofc MyScriptable.
And remember that the myScriptable instance will be serialized in edit mode as soon as you finish compiling the script for the first time, since you put CreateInstance inside OnValidate().
EDIT
You're getting the Type Mismatch error in the prefab of the game object with the MyComponent script, and that's normal, since prefabs can't get a reference to any kind of instances in the hierarchy of the scene, but only to assets.
For example, if you create a game object in the hierarchy, then attach the MyComponent script, you'll be able to access the myScriptable instance, by double-clicking on the My Scriptable field of the script in the inspector.
But, if you now create a prefab from it, you'll get the Type Mismatch error in the field of the script attached to the prefab.
And you can't really escape from it: if you want to have a reference in the prefab, you HAVE to create a myScriptable asset which can be then referenced by the prefab.
Of course you can do that by using
AssetDatabase.CreateAsset(myScriptable, "pathname+assetname.asset");

just after the CreateInstance method in MyComponent, or you can add the [CreateAssetMenu] attribute in the MyScriptable script, so you can create any asset you want in the editor, and then drag-and-drop it in the reference field of the prefab.
That's pretty much it, hope it helped.

Sorry, I free-typed and missed that part. The two classes are in different files and the files bear the name of their respective class name. Nothing seems to be serialized though. Instead, I get a "Type Mismatch" error in Unity, in the Object field where myScriptable is supposed to be.

Ok, I managed to recreate/understand the "bug", bug inside the quotes because it's not really a bug. I'll edit my answer to explain the situation and how to fix it.

Thanks for your answer but my question is about NOT creating an asset from it.

"if you want to have a reference in the prefab, you HAVE to create a myScriptable asset which can be then referenced by the prefab." - which part of this sentence isn't clear?

Sorry, I missed that line among your explanation on how to create assets.


text:
Are closing window and destroying DirectX11.1 independent?
I have a project with DirectX support.
In this program uses two threads.
One is a dedicated message loop and the second is executing DirectX API's.
The question is about ending such program.
The WM_CLOSE sends asynchronous command, that stops rendering and exits DirectX loop too. After that it destroys the window.
Everything works fine. The question is, is this algorithm OK?
Should the window's thread or the DirectX thread be synchronized (dependent)?

The main area of synchronization is between your 'windows thread' and the thread you call 'DXGI' from for Present.

I highly appreciate the answer.

The main area of synchronization is between your 'windows thread' and the thread you call 'DXGI' from for Present.
See Microsoft Docs.

When executing, you need to be careful, if the close starts releasing our impacting resources in your windows main thread, this can affect your DirectX thread.  As another answer has indicated, the Present is your point of Sync. You maybe best to at the least use some atomic flags cross the threads to ensure that your close action has not started at the same time as you are entering a critical part of your draw execution.
If for example, you built a synchronous close function called from your parent thread that waited on other child threads to complete and close then that is one approach.  Once you start into the world of deferred contexts and further multi-threading your game.  A common sync point for critical system action will be more important (actions such as close).
Having gone through the multithreading pain myself, the key point I have found is that destruction of objects in child threads causes all sorts of headaches.

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


text:
Why is Unity ignoring my camera on Android?
I am making a TV remote app for a specific android device (the Pixel XL, 1440x2560 resolution). However, when I put the app on my phone, it truncates most of the app.
Here's what it should look like:

Here's what it ends up looking like:

My game is forced in portrait, and I want to keep it that way.
I have tried rotating the canvas, but that does nothing. The Android app also seems to ignore the main camera; I think it is just using the canvas.
I tried many different things, including changing the scaling and setting the anchors.  None of this had any effect. I have even set the editor Game window to the target resolution, but it appears to work via the editor.
Why is Unity ignoring my camera on Android?

Forcing landscape cuts off much less, but I want it in portrait.  I've also tried rotating everything, but it has the same effect.

Yeah, I'm aware of this (really the only thing I am aware of), and I've tried this and it works in the render (somewhat).

I just deleted the main camera and re-added it.  It now is displaying nothing.  Know why this might be happening?

It is truncating; actually, your UI is not responding to the resolution of your device. You have to set its anchoring and scaling. I would recommend you read the Unity guide for "Designing UI for Multiple Resolutions"
For a reference, this what you have to change:

In the Canvas Scaler component, you can set its UI Scale Mode to Scale
With Screen Size. With this scale mode you can specify a resolution to
use as reference.
...
When the screen size is changed to a larger or smaller resolution, the
buttons will also remain anchored to their respective corners.
However, since they keep their original size as specified in pixels,
they may take up a larger or smaller proportion of the screen. This
may or may not be desirable, depending on how you would like your
layout to behave on screens of different resolutions.

Okay, the resolution is set to the exact resolution of the phone, and it's still doing this.  As someone already suggested, I'll try the anchors tonight when I have access to my app

Setting the anchors had no effect.

post some more information in the question.with snapshot of your UI with canvas

What information exactly?

as i told you before select you canvas and make screen shot of your canvas in scene view

I want to look that how you are doing . is your image inside of canvas

Here's an image: http://imgur.com/AEk6wTp.png  (I can't upload more than 2 to the original post).

why you have change UI to world space?

I tried all 3, none worked.

it will be screen space. i can't figure out what it the problem can you upload that project with only canvas problem.

How do I do that?

add Minimum project with canvas (UI problem) to google drive and provide me its link

I'm not quite sure how to isolate the problem, would you like the whole file?

There's so many possibilities for your problem. Basically, you can try these and if it will not work then you should to give more information about your scripts components etc.
Check your Canvas' UI Scale Mode, it should be Scale With Screen Size
If it is then check your sprite what's look like in the Inspector. Attention to Pixel Per Unit factors.
If everything is okay then check the Canvas-UI element's anchor. And see the spread of UI elements (like buttons) in the screen.
Did not works ? Give us to more info and let's write a camera script.

The UI Scale Mode is "World" and grayed out.

I tried changing Render Mode to "Screen Space - Overlay" and "Screen Space - Camera", and UI Scale Mode was set to "Scale With Screen Size", which didn't work on either.

Not quite sure what you mean by Pixel Per Unit, the Reference Pixels Per Unit for the canvas (under inspector) is 100.

Hmm, I think your problem with the anchors. Add a new button into your Canvas. (Example) Click the Anchor Presets and Click Right. The button will not leave the right edge anymore. You should try to find best  with move the anchor presets.

I'm not quite sure what you mean, I created a new button and found the Anchor Presets.  I clicked right, and it appears to snap to the top of the image (or the right of the remote, on the side with the 3, 6, and 9 keys).  It snaps with a blue line, but I'm not quite sure what you want me to do from here.  I'm having trouble understanding what "You should try to find best with move the anchor presets." means.

You just have to find correct position to move items' anchor (which looks like a clover). For example; for gear button click  bottom right, for turn on/off button click the left corner. That means if screen size will change it set the position from anchor position (Independently of button's position). You can move the buttons whereever you want, you just responsible for anchor. I hope I explained clearly.

Ah okay.  I think I understand what you're saying.  Unfortunately I don't have access to Unity until Tuesday night, but I'll try it then and post my outcome here.  Thanks for the help!

Setting the anchors had no effect.


text:
How should you save sprites for talking and blinking characters?
Lets say you have a game like Phoenix Wright: Ace Attorney, where characters appear on screen and do things like:

change their stance/pose depending on the situation and mood (looking happy, looking sad, looking at the camera, looking to the side, etc.)
move their mouths while their text is printing out
randomly blink
do other stuff (getting pecked by a bird for example)

I'm not sure how I should go about saving all those different "sub animations" in my spritesheets. Should everything related to one character be saved in one huge spritesheet? Or should all those sub animations have their own separate spritesheet? Should I save ALL blinking related sprites in one spritesheet or should I keep them separate from each other (one spritesheet for the blinking sprites of the happy pose, one file for the sad pose, etc)?
I would like to know what the preferred approach would be from a technical and "artistic" standpoint:

What's the best way to save up on space and make sure the game handles the sprites well?
What "format" would be preferred for the guy actually creating those sprites? I don't mean format as in file format or even a tool specific for the creation of spritesheets, but more HOW the sprites are arranged on the spritesheet(s).

Since the main advantage of having sheets is to able to load multiple the sprites at the same time, and not have to switch textures to use them. The pragmatic criteria is how will you load them. So, try to keep things together (as much as file and texture size allows) in this order: all the sprite of an animation of a character, all the sprites for animations around the same pose of a character, all the sprites of a character. Choosing format is broader, my advice is to see what formats are common for your engine / platform and choose among those the easier to use for you that will work.

@Theraot Sorry, I should've been more clear with what I mean with format: not talking about file format actually, more like how the sprites should be arranged in the spritesheets. Edited my question for clarity.

Format and layout doesn't really matter for the artist because you can process and pack the sprites to take up less room.
You can tell the artist to save each sprite in a separate file and make everything that is not part of the sprite fully transparent.
Then you use a tool to go over every sprite and find some tight enough enclosing geometry and then go and pack several of them into a single sheet. while making sure there are no overlaps. Prefer packing sprites that you need together into a single file. For example all the frames of a sobbing animation would go into the same file.
You save the layout of each sheet so you can index them by the original file name (or whatever you use as sprite identifier) so you can create the geometry to display it at runtime. Make sure to discard the pixels that are fully transparent.
This allows you to add hot-loading of new sprites easily. Your engine can then monitor a directory of raw files with 1 sprite each and each time a file is updated in it you and then loading the updated file and letting it override any previously loaded sprite with the same ID.


text:
How can I render an OpenGL scene into an ImGui window?
The picture rapresents what i want to achieve.

I read, somewhere on the Internet, that you can render the fbo and pass that fbo as a texture to render into the ImGui window. The problem is that I don't even know what an FBO is, and how to create it. I just want to have the scene rendered into my ImGui window (just like the scene window in Unity)
How do i do it?

First you need to render you scene to a Frame Buffer Object (here is a good course on FBO: https://learnopengl.com/#!Advanced-OpenGL/Framebuffers)
After that you will end up with a Texture (of type GLuint) containing your rendered scene. To print it into Dear imGUI, just call a Draw Image Command.
EDIT New (simpler) Example:
ImGui::Begin("GameWindow");
{
  // Using a Child allow to fill all the space of the window.
  // It also alows customization
  ImGui::BeginChild("GameRender");
  // Get the size of the child (i.e. the whole draw size of the windows).
  ImVec2 wsize = ImGui::GetWindowSize();
  // Because I use the texture from OpenGL, I need to invert the V from the UV.
  ImGui::Image((ImTextureID)tex, wsize, ImVec2(0, 1), ImVec2(1, 0));
  ImGui::EndChild();
}
ImGui::End();

Previous Version
Here is an example:
// My Game has a different viewport than the editor's one:
const int W = 1080 / 2;
const int H = 1920 / 2;
// We set the same viewport size (plus margin) to the next window (if first use)
ImGui::SetNextWindowSize(ImVec2(W + 10, H + 10),
                           ImGuiSetCond_FirstUseEver);
  ImGui::Begin("Game rendering");
  {
    // Get the current cursor position (where your window is)
    ImVec2 pos = ImGui::GetCursorScreenPos();

    // A boolean to allow me to stop the game rendering
    if (runApp) {
      glViewport(0, 0, W, H);
      // Render the scene into an FBO
      game->render(time);
      // Restore previous viewport
      glViewport(0, 0, w, h);
    }
    // Get the texture associated to the FBO
    auto tex = game->getRendered();

    // Ask ImGui to draw it as an image:
    // Under OpenGL the ImGUI image type is GLuint
    // So make sure to use "(void *)tex" but not "&tex"
    ImGui::GetWindowDrawList()->AddImage(
        (void *)tex, ImVec2(ImGui::GetItemRectMin().x + pos.x,
                            ImGui::GetItemRectMin().y + pos.y),
        ImVec2(pos.x + h / 2, pos.y + w / 2), ImVec2(0, 1), ImVec2(1, 0));
  }
  ImGui::End();

I don't understand what the the last two parameters of AddImage mean

These two ImVec2 are UV mapping

but shouldn't it be (0, 0), (1, 1) instead?

In my case UV mapping required to be flipped. Sorry for the late answer.

What is ImVec2(ImGui::GetItemRectMin().x + pos.x, ImGui::GetItemRectMin().y + pos.y), and ImVec2(pos.x + h / 2, pos.y + w / 2) ? I got working the  fbo and the texture is correct(i applied it to a quad) but the imGui window is not displaying it correctly..

Ok i got this. The 2nd and 3rd parameters are the upper left and lower right corner of the image inside the imgui window

Rendering to a FBO and using as a texture is just fancy speak for rendering to texture and then using that texture in a subsequent render. All geometry generated by imgui are just texture triangles.
FBO stands for FrameBuffer Object, it is a collection of images that you can use as a rendertarget. Opengl is initialized with the window as the default target FBO.


text:
Downloading a file with UnityWebRequest
I need to download a file (a .ogv video) from a server using a UnityWebRequest.
Let's say the file is located at home/folder1/folder2/file.ogv on the server, and the IP adress of the server is 1.2.3.4. I tried to create my web request with:
webRequest = UnityWebRequest.Get("1.2.3.4/home/folder1/folder2/file.ogv");

However when this web request is sent, nothing happens.
webRequest = UnityWebRequest.Get("1.2.3.4/home/folder1/folder2/file.ogv");
DownloadHandler receiveBundle = new DownloadHandlerBuffer();
webRequest.downloadHandler = receiveBundle;
webRequest.Send();

Sorry, I edited the question. The previous error message was due to a typo.

Have you tried accessing the file from a web browser? The most likely reason you can't access it from Unity is because it's not accessible at all.

You were right, I put my files in another server and something happened (meaning some files were downloaded this time). However, I still have a problem as the downloaded files are all 1kB. Should I edit my answer to reflect this?

Can you post the full log? any error or response you are getting from request you made?


text:
OpenGL ES wrong orientation
I'm writing a little Android game in OpenGL ES. My game graphics are not appearing in the right orientation. In fact everything is drawn in reverse vertically. Can someone please comment on my understanding of how OpenGL works below please?
My understanding is that OpenGL works in a right handed coordinate system, e.g.

        y(+)
        |
        |
        o-----x(+)
       /
      /
     z(+)

So, I set my orthographic projection matrix using
Matrix.orthoM(..., -2, 2, -2, 2, 1, 15)
for example, so if I were to draw a line from (-2, 2, 0) to (2, -2, 0) I should be drawing a line in the X/Y plane from (-2, 2) top (2, -2). Near and far planes are 1 and 15 respectively.
In addition I am setting up my view matrix using
Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 10, 0, 0, 0, 0, 1, 0)
so I'm standing on the positive Z axis at 10 units, looking towards the origin with the Y axis as the upwards vector.
But when I come to draw stuff, everything is flipped in the X axis. So a point at (1, 1) would appear at (1, -1).
Does anyone see what might be wrong here?

OpenGL's co-ordinate convention is that bottom-left is the origin; this matches e.g. a mathematical graph but not screen co-ordinate conventions.

My current set up has the view matrix on the positive z axis looking a the origin with Y as "up". and the ortho matrix is [-2,2]x[-2,2], so as I understand it the point (1.5, 1.5) should appear in the top right part of the screen...


text:
The largest vector in an array
I'm working on a game engine in C# at the moment and I've come across a matter I find confusing. I need to know how to get the maximum three component vector in an array.
There is a method in OpenTK that can compare two Vector3s to find out the max, I need this on a larger scale.
I've tried using Array.Max(), but I get the error :

At least one object must implement IComparable

You can extend the Vector3 class and implement the interface IComparable, this let's you use every generic method which requires IComparable to be implemented, such as Sort() Max(), ... https://msdn.microsoft.com/en-us/library/system.icomparable(v=vs.110).aspx

Are you trying to compare the length of the vectors? It's unclear from your question. Vectors are not normally orderable unless you define a function of their components, such as length.

Another possible interpretation is that they want a single vector whose x component is the maximum of all x components in the array, whose y component is the maximum of all y components in the array, etc. One might use this, for instance, for computing the corners of an axis-aligned bounding box around a set of points. Without more explanation though, it's impossible to tell what the intended result is.

Linq method of solving this would be using MaxBy coupled with a method mapping vector to a scalar type, e.g. LengthSquared or ComponentMax which gives float,
var resVec = array.MaxBy(vec => vec.LengthSquared);

This is the most intuitive answer.

Having a look at the Vector3 class of monotk gives us a hint why this doesn't work. Classes such as Sort() and Max() require your datastructure to implement the IComparable interface, which requires the CompareTo() method.
With this method you define a new binary relation. You can implement a lexicographical relation (aa > ab (this only works because the characters are ordinal) ) for strings, use distances if your class is a topological graph,...
Comparing two vectors ( dimension > 1) isn't so straight-forward. Which vector is greater: (100,10) or (10,100) or (67,43)? To compare vectors in a metric space, you have to rely on a norm. You might however want to create a different ordering, such as: First compare the Y coordinate, then the X coordinate. This gives us (for points) all the points sorted row by row.
As you can see, it is not trivial to compare vectors, and different use cases need a different definition of "the greatest of two vectors". The trivial case, where you want to know if two vectors are equal, is implemented (overloading the == and != operator).
Now what? You can extend the Vector3 class and implement the IComparable interface to be able to use Array.Max(). Or you can simply create a loop and compare your vectors on your own, and define what you want as "max". You can compare their norms, or use the implemented ComponentMax() functions, which compares the vector by, you guessed it, components.
All in all, once you defined "your maximum vector", the implementation is straight-forward.

You can do this in linear time:
Vector3 best = yourArray[0];

for (int i = 1; i < yourArray.Length; i++)
{
    if (yourArray[i] > best)
        best = yourArray[i];
}

Are you sure that the > operator is defined in the Vector3 class in opentk?

@lyinch I don't know,  but he said that there's a method doing that

is not defined. He is referring to the Vector3 ComponentMax(Vector3 a, Vector3 b) method.

@lyinch I didn't give him an exact code to use, I gave him the basic way to solve this problem, if he knows anything about programming, he'll be able to change it according to it


text:
How can I fill the interior of a closed loop on a tile map?
In my game the player can dynamically modify terrain.  The map is stored within a 2D array of prefabricated 3D objects.  This is working well for now.  The player modifies terrain by selecting what sort of tile they'd like to create (like cliff going up or down), and then clicking individual tiles, or "painting" over multiple by holding down mouse button and scrolling.
I don't want the player to have to manually click every tile they want to rise or fall in elevation.  The most elegant solution I can conceive, is for the player to "paint" a loop of cliff tiles, which is then filled in automatically when the loop closes.  Imagine, perhaps, someone drawing a line using MS Paint or Photoshop, until that line closes into a shape which then autofills.
Let's say the player wants a plateau, and so they select cliff going up, and then click and drag the desired shape.  Upon closing the loop, when the last cliff tile is created beside the first cliff tile, witchcraft is invoked which fills the inside.
I have no idea how this can be done, never mind elegantly or optimally.  There are obvious possible solutions (find the average vector of all tiles in the loop, and then dijkstra algorithm from the average until the space is filled with the correct elevation), but these assume the shape generated is blobby or boxy.  An irregular shape where the mid point falls outside of the shape is possible and would probably ruin that solution!
How can I fill the inside of a closed loop? I'd like a theoretical solution I can go away and implement in C#.  At this point it seems like there is probably conceptual overlap between raster graphics and procedural maps!

Short: After completing the shape you should have a multiple of 2 Points for each affected row on your x-axis. From there it becomes just a matter of splitting up these Pairs of Points for each row and then fill the inbetweens.

Long1: This is not a complete algorithm. This is just a description of steps to be taken. How to achieve each step is up to the reader and might differ between languages, etc.

Step 1: Draw the loop inside your game/editor/whatever and however you want to do that.
Step 2: Get the points touched by your loop. These are the edges of your shape.

Step 3: Iterate over these points and get the ones that have one or no neighbours. These are our starts and stops (or whatever name you find fitting).
Step 4: Iterate over your starts/stops and create pairs of two each.
Step 4b - Special Case: If you've got an odd number of stats/stops you can get rid of the central point.

Step 5: You can now fill the area2 between each pair of points.
1WITH PICTURES! I KNOW, RIGHT?
2Well, it's actually segments not areas. A line between two points is a segment. The whole thing is an area though.

As mentioned in the comments this algorithm is not bulletproof at all, here's one proposed improvement to Step 4b by @DMGregory

Can you elaborate/reiterate this?  I'm confused by the terminology.

@inappropriateCode might be the language barrier, though I looked up the terms to make sure I'm using proper geometry words. I'll make a graphic.

It is probably my ignorance of geometric terminology!  Will appreciate any editing to reiterate such points, thanks!

@inappropriateCode done

@inappropriateCode anything still unclear? :) It also really doesn't matter if you work the x dimension or the y dimension. You could even work both and then overlay the results or something like that.

I love this answer. The special case isn't just for rows with an odd number of points though, it's for points whose predecessor / successor are both on the row above or row below, so the loop just "kisses" this row at one point. You'll want to filter out all such points like these, even when the row contains an even number of points in all - otherwise your fill will leave a gap between the two kissing points.

@DMGregory I gather you are talking about using special tiles on the edges, right? You can either make the algorithm check above and below... Or you can just run it twice once for x and once for y. Then you can overlay your results and thus determine where special tiles such as corners, etc. are put

@dot_Sp0T Couldn't see images at work, now can.  This looks excellent, I shall have a stab at implementing it in the coming days!  Thanks again!

@inappropriateCode it's using the stackexchange image upload, which hosts in term on imgur. Probably blocked at your workplace :)

@inappropriateCode I also hope my handwriting is readable enough..

Some pseudocode for step 3 while iterating left to right. if (tile.full == true && tile.left.full == false) { Recursion(0, tile)} Inside of recursion: if (tile.right.full == false) return tile; else Recursion(iterator + 1, tile); That gives you your 2 points. then you continue along the loop as normal. You could, if you wished, jump into a new function to loop inside of your chosen points and fill in as you go. This way, you wont need to loop through your segments afterwards, you can just store one Segment, fill it in then drop it. Or, fill the tiles inside of your recursive function.

Very nice explanation, but I can't figure out how you know that the extra odd point is the central one. Just add an additional arm to the blob that crosses line 8, say on the right, and the odd point is not the central one anymore.

@Quentin well, it's definitely not perfect. You could probably do a lot by either checking up and below each point as well, or by doing a second run on the y-axis and overlaying the results.

I've drawn up an example where the "ignore the middle point in odd rows" rule leads to incorrect fills. https://imgur.com/a/KDfWW Instead, as described above, I'd recommend ignoring points that only "kiss" the row or do a U-turn, rather than crossing through/along.

That looks amazing! Thanks. Does this algorithm have a name or does it resemble a certain group of algorithms?
I would like to learn a bit more formally about such approaches.

sry, this thing came into existence out of wanting to solve a not-that-difficult-seeming-problem. in the end it's neither a full algorithm, nor an optimised one. it's as good as anything that solves an issue, and has it's own shortcomings (part of which DMGregory already created a 'fix' for). When creating a game, or writing code in general, you should not start with striving for the best solution, but start with getting something working down fast - that's what this algorithm ultimately is

For simple shapes (i.e. ones that don't self-intersect, so that the interior of the shape is a single connected area) a flood fill algorithm should work fine.
The tricky part of trying to flood fill the interior is that, as you note, you'll need to start the fill from a point that you know to be inside the loop.  One way to find such a point could be to pick, say, a point just south of the northernmost point in the loop.  As long as your loop shape is clean enough, and doesn't double back on itself, you could be pretty sure that this point will be inside the loop.
However, there's an alternative solution that avoids the need to find such an interior starting point completely, and also handles arbitrary self-intersecting shapes:  instead of flood-filling the inside of your loop, fill the outside instead.
Of course, it's probably not practical to fill all of the outside, since your map will likely be a lot bigger than the shape drawn by the player.  But it's pretty easy to compute a bounding box that encloses the shape drawn by the player (and extends at least one map tile around it on all sides, to make sure there's a connected path around the shape inside the box), and then flood-fill the part of the box that lies outside the shape, starting e.g. from any corner:

The interior of the loop will then consist of every point inside the bounding box that has not been touched by the flood fill algorithm.
The nice thing about this algorithm is that it's dead simple to implement, especially if you're already familiar with things like Dijkstra's algorithm, which is basically a special kind of flood fill.  Unlike the scanline fill algorithm suggested by dot_Sp0T, there are no tricky special cases with corners or with boundary lines that align with the grid; all you need to do is make sure the boundary is continuous and closed, and then flood fill its exterior.
Note that, if the player's loop can self-intersect, these algorithms can give different results.  For example, for the self-intersecting boundary shape shown in the image below, the even/odd fill rule obtained from a scanline fill would fill in the purple area on the left, while the exterior flood fill algorithm I describe would treat the entire cyan area on the right as being inside the loop:

It's up to you which behavior you'd consider more reasonable.  (Of course, other fill rules are also possible, such as the non-zero winding rule, which would fill in the upper "hole" in the shape above, but not the lower one.)