text:
How can I make bullets come from a character's eyes, but look like they come from the gun?
How can I make bullets in a first person shooter look like they come from the gun, but actually come from the eyes of the character? The problem is that since the camera (the character's eyes) are in a different position than the gun, bullet animations coming from the gun won't end up at the crosshairs. This guy manages to do it, and it's more obvious at 5:17 when the bot is shooting at him. This also happens in CS:GO
I was thinking that maybe the final destination of the bullet is calculated, and then the path is traced backwards to the gun from there, but it's just a guess.

Offset to guns position? Find the delta between camera and gun and add it to bullet for its initial position?

The reason that bullets coming from the gun don't work with the cross hair is because the cross hair represents where the bullet would go at an infinite distance.
You can't make the bullet look like it comes from the gun but actually come from the eyes without causing some problems.  Specifically, where the bullet looks like it's going and where it hits won't be the same place.
The Problem
Here's a set of illustrations that show how/why I say this...

First, this is a representation of a player shooting from the hip.  The red dot represents where the cross hair aim point.  The horizontal green line is the view from eye to aim point (through cross hair).  The red line coming from the gun is the actual bullet travel line.

Here is the same setup if the shooter is holding the gun up (iron sights).  This is what's happening in the example you reference in the video at 5:17.
Now let's go back to the first case, but add a target that's in front of the player, and fairly close.

You can see now how where the cross hair looks like it's targeting and where the shot hits isn't the same.  And that's a problem, because it might actually mean a miss if the hit boxes are more complex, or if you are rendering a hit decal at the impact point.  Either the player shoots at what looks like a perfect target and misses, or the player shoots and hits, but the hit indicator isn't where they shot.
But of course if they are holding the gun up to their eyes (iron sights), it's just fine...

The Solution
First, here's the problem we want to solve.  We want to hit the spot that the cross hair is on, like this...

The first thing you need to do is calculate where the point is that your eye is on the target.  In other words, calculate where the line drawn from eye to aim spot (cross hair) would hit.
Once you have this point, there are two things you should do.
First, when you draw the streak of the bullet, draw it from the tip of the gun to this newly calculated point...

It's not super clear in my illustrations, but the problem is though your gun isn't quite pointing the same way as the shot.  And the closer the target is to you, the worse it will be.  So the second thing to do is rotate the first person gun model up a bit so it's pointing at the impact point, like this...

And now, everything is all good!
It might look a little bit off if the target were literally right in front of the player - like if they were face into a wall.  You can actually fix this by having the player lift the gun up more as the target gets closer, so the rotation is less.
Alternate Solution
If the gun has a laser sight, then you will always be calculating that point where the laser (coming from the gun) illuminates the target.  When the player shoots, the bullet hits where the laser sight is.  It is maybe a little disconcerting that the cross hair and the laser illumination dot aren't in the same spot, but it does help a bit.

You just need to use basic geometry.
If you know the distance to the target and you know the distance between your character's eyes and, for example, the weapon's muzzle, you simply apply the Pythagorean Theorem and get the distance from the two points (muzzle and target).
Then you get the direction vector by
Vec3 direction = (targetPosition - muzzlePosition).normalized()

Now you can spawn a bullet in the position of the muzzle with that direction vector.
You can calculate whether the bullet would hit or not by raycasting from the eye's position and how much time the bullet would need to get from the muzzle to the target by using the formula
Time = distance ÷ speed

Having that time you can play around with bullet spawning, special effects, sound, etc.
Hope it helps. Update the question and comment if there's anything else or unclear.

It's relevant to note that most games do not use the bullet object to detect hit, as bullets move in very high speed and are expensive to check collisions with.
Instead, animate the bullet coming out in a way that looks good and calculate the hit point by using something like a raycast.
That way you won't face the problem highlighted on the other answer that involves the reticle being at the infinite distance.
Also, while this may seem like it can only work for instant shooting (the bullet travels at infinite speed and hit all it's trajectory at once). However, you can shoot these days with limited length and every x frames you can angle the shot down (to simulate bullet travel) and send a new raycast.
Important to note, this "angling down" is just in the variable space, the visual of the bullet does not matter for this.


text:
How to scale game with orthographic camera correctly?
During porting to android I encountered that the game does not fit on the screen in portrait mode. It uses an orthographic camera. How could I scale to game to fit the screen in portrait mode?

You'll have to define for use what "correct" scaling looks like for your game, compared to what you're getting now. There's a lot of ways we might try to scale/frame a game to work in a different orientation, depending on what your gameplay and visual style demands.

The game is simply doesn't fit on the screen. With correct scaling I mean that the game is fully visible.

What does "fully visible" look like for your game? Include examples in your question to make sure you get accurate, applicable answers.

I think with the current description the problem should be already understandable, but I will include screen shots.

You can change the "zoom factor" by using the orthographic camera's size (in editor) or orthographicSize (in code) parameter. You can get the aspect ratio (with/height) from the aspect variable on the same camera.

And how should that solve my problem?

It sounds like you want to add letterboxing bars above and below the game scene, shrinking the vertical height until the horizontal fits. You can find a script that will do that here: (Unity Android) How to force keep the aspect ratio and specific resolution without stretching the output screen view?

source: Stack Exchange

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

sort: votes


text:
IOS very simple 2d engine/api rendering showdown
So after taking some time running through a course, I believe I have enough experience with referring back to the course how to make the game I wish to all apart from one thing. How to draw the game on screen, I know how the game would work behind the screen, but don't know how to draw it. I'm looking for an experienced, informed answer based upon certain factors.
To provide some context, the game in question's interface would be very simple:

Grid of lines
Control each cell's content: (text and colour)
Pan and zoom

The game at the minute is based upon an excel spreadsheet as shown to show how simple it is:

My aim to keep this question open to others is to create a pros and cons of each.
I've narrowed down possibilities to this list. These are taken from the apple developer page under the section 'Graphics and Games':

Core Animation
Core Graphics
GLKit
Metal
OpenGL ES
cocoas 2d?
Other Noteworthy

I'm asking for an informed opinion as to which I should choose. This is narrowed down from research, however I assume I will have missed things that may make this task much easier. My problem thus far is that most games assumed I needed sprites but in something this simple I'm assuming I don't.
If it makes any difference, my current knowledge is only swift, high school math and hopeful abundance of learning resources. I've been stuck with this problem for a long time and I would be overjoyed if I could get some experienced advice. Thanks! :)

This should really be chosen by you. Questions like these are discussion oriented, so it's offtopic on this site

This question is not discussion oriented.  Any familiarity with the frameworks lead to an undeniably simple answer.  Unfortunately, gamedev.SE tends to decide far, far too much is "discussion oriented" or "off-topic".  Which framework is best for a type of game is exactly what gamedev.SE works best for

Aaaand it was put on hold as off-topic anyhow.  Because of course it was.
Just because you, high-gamified-score-holders don't understand how the question could be answered objectively doesn't mean it cannot be.

The options provided are unsuitable to the task you've described.  Apple has created a framework that works very, very well for 2-dimensional games called SpriteKit
To be precise:
Core Animation and Core Graphics are lower level than you need.  These are more suitable to a single simple task that cannot be easily reproduced by sprites, like a simple painting app.
GLKit, Metal, and OpenGL are far more complex and flexible than is needed.  They require much more expertise than would ever be expected or reasonable for a game/engine of this scope.  These systems allow for very complex graphical feats and would be more appropriate for detailed, resource-intensive 3D games, custom shaders, and the like.
SpriteKit, however, is designed to be a high-level, simple-to-use sprite-based framework.  For the engine you described, you would not even need any "sprite" resources, as the entire engine seems to be nothing more than squares and text.  The entirety would be renderable (size, color, and text) with no outside resources, yet would remain extensible should you desire to add custom sprite functionality at a later point.  The "camera" controls would be simple in SpriteKit, while the squares, color, and text would be trivial.

are you saying each square would be a sprite? To my knowledge you would 'build' your view out of objects in this case the squares, rather than drawing the lines. I would've thought in this case holding all those squares in memory would be a burden?

Yes, each sq. is a sprite. No, they wouldn't be a burden. SpriteKit would actually only load one sprite in memory if you used a "square" sprite, but you might not even need to do that, since sprites are rendered onto square/rectangular shapes at their foundation.  Simply create SpriteNodes with no set sprite, set the color, and you're done.  Place text constrained in the same size of a square as a child, and you have a square with text.  Place a smaller square as a child of a larger square, and you have a square with a border.  The resource use would be trivial

Thanks very much, I probably wouldn't have looked into it due to my preconceptions of it. After some research based on your answer, would you recommend using a 'tile map node'?

Nevermind, that's for textured sprites.

Given what you've provided, I would probably just do it with CoreGraphics. Learning OpenGL or Metal is a big task. (You should do it eventually, but learn simpler stuff first.) You can easily draw the board and update it when moves are made. You can make a view that's as large as you need and only draw what's been revealed as panning happens and it should be performant enough for your needs as described here.
If you keep the drawing separated from logic of the game you can always throw out the drawing and replace it with something better as you learn other technologies.

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


text:
Want some limits in Bullet firing and its stop when i press the shoot button
I want some limits or range when my player fire the bullets and when i press the shoot button my fire as been stopped. I use the GetButtonDown from this its fire continuously but its not stopped. and if i use Input.GetButton than its hold the button and fire continuously but in fire there is no gap. So, my problem is that how i stop the bullet fire when i press the shoot button and if choose this (INPUT.GETBUTTON) and its hold the shoot button and its fire continuously than i  want some gap on that fire and some limits or range of fire.
void Update(){
        if(Input.GetButtonDown("Fire1"))
        {
            shootRoutine = StartCoroutine(PlayerShoot());

        }else if(Input.GetButtonUp("JumpButton"))
        {
            StopCoroutine(shootRoutine);
            shootRoutine = null;

        }
    }

    void JumpButton(){
        if(!transform.GetChild(0).gameObject.GetComponent<PlayerHealth>
            ().hasDied){
            if (grounded){
                grounded = false;
                myRigidBody.AddForce (new Vector2 (0,
                    jumpPower), ForceMode2D.Impulse);
                if(myRigidBody.velocity.y > jumpPower){
                    myRigidBody.velocity = new Vector2 (0,
                        jumpPower);
                }
                animator.SetBool ("isGrounded", grounded);
            }
        }
    }

PlayerShoot method
IEnumerator PlayerShoot()
    {
        while(true)
        {
            if (!transform.GetChild
                (0).gameObject.GetComponent<PlayerHealth>().hasDied)
            {
                if (energy >= 5f)
                {
                    //energy -= 5f;
                    energyLevel.value = (int)
                        energy;
                    energyText.text = (int)energy
                        + "%";

                    GameObject newProjectile =
                        Instantiate(projectile, new Vector3(transform.position.x + 1.5f, transform.position.y - 0.02f,
                            transform.position.z), Quaternion.identity) as GameObject;
                    if
                        (GameController.instance.isMusicOn)
                    {

                        AudioSource.PlayClipAtPoint(MusicController.instance.audioClips[2],
                            newProjectile.transform.position);
                    }
                }
            }

            yield return new WaitForSeconds(shootDelay);
            //Wait for 'shootDelay' seconds before starting over again.
        }
    }

I think you should stop the shoot coroutine when you detect Input.GetButtonUp("Fire1")

Try something like this. I got rid of the coroutine, tell me if it's ok for you
private float lastShootTime = 0 ;
private PlayerHealth health ;

public Graphic button; // Drag and drop a UI image / Raw Image
private bool buttonDown = false;

// Indicates whether the player can shoot
private bool canShoot
{
    get { !health.hasDied && energy >= 5f && Time.time >= lastShootTime + shootDelay ; }
}

void Start()
{
    // Retrieve **once** the PlayerHealth script
    health = transform.GetChild(0).gameObject.GetComponent<PlayerHealth>();

    // Add event listeners to the button to detect whether the user is holding the button
    button.raycastTarget = true;
    EventTrigger eventTrigger = button.GetComponent<EventTrigger>();
    if (eventTrigger == null)
        eventTrigger = button.gameObject.AddComponent<EventTrigger>();

    EventTrigger.Entry pointerDownEntry = new EventTrigger.Entry();
    pointerDownEntry.eventID = EventTriggerType.PointerDown;
    pointerDownEntry.callback.AddListener( (data) => { buttonDown = true; } );
    eventTrigger.triggers.Add( pointerDownEntry );

    EventTrigger.Entry pointerUpEntry = new EventTrigger.Entry();
    pointerUpEntry.eventID = EventTriggerType.PointerUp;
    pointerUpEntry.callback.AddListener( (data) => { buttonDown = false; } );
    eventTrigger.triggers.Add( pointerUpEntry );

    EventTrigger.Entry pointerExitEntry = new EventTrigger.Entry();
    pointerExitEntry.eventID = EventTriggerType.PointerExit;
    pointerExitEntry.callback.AddListener( (data) => { buttonDown = false; } );
    eventTrigger.triggers.Add( pointerExitEntry );
}

void Update()
{
    if( buttonDown && canShoot )
    {
        // No coroutine anymore
        // The "wait" between 2 bullets is handled inside the `canShoot` property
        Shoot();
    }
}

// Shoot the bullet!
private void Shoot()
{
    energyLevel.value = (int) energy;
    energyText.text = (int)energy + "%";

    Vector3 projectilePosition = new Vector3(transform.position.x + 1.5f, transform.position.y - 0.02f, transform.position.z)
    GameObject newProjectile = Instantiate(projectile, projectilePosition, Quaternion.identity) as GameObject;
    if (GameController.instance.isMusicOn)
    {
        AudioSource.PlayClipAtPoint(MusicController.instance.audioClips[2], projectilePosition);
    }
    lastShootTime = Time.time;
}

its work thanks :) but when i jump its fire.

If you want to prevent your player from shooting when jumping, add grounded at the end of the condition inside the canShoot : get { !health.hasDied && energy >= 5f && Time.time >= lastShootTime + shootDelay && grounded; } Also, make sure your coroutine PlayerShoot is removed from your code and you don't call Shoot outside the Update function

actually my player fire with specific gap but i touch anywhere on the screen its fire.

I suppose your game is a mobile one, and I guess you want to have specific  on-screen buttons to fire? Then, I invite you to read this thread to detect touch events on ui gameobjects.

Yes it is for mobile purpose. so, what to do for my buttons?

Check my updated answer ;) I've added some code to detect whether the player is holding the fire button down.

are you please provide me your mail id? because i don't have 20 reputation and i want to discuss some more about my game.

Sign in to the Unity forum and send me a private message from there ;)

I ping u there, please check it!!


text:
Unity: Component not being serialized
I have a script like this:
public class A: MonoBehaviour {
   public bool x = false;
}

... and a Custom Editor like this:
[CustomEditor(typeof(A))]
public class A_E: Editor
{
   public override void OnInspectorGUI()
   {
      A a= target as A;
      if (a== null || a.gameObject == null) return;
      a.x = !EditorGUILayout.Toggle("x", !a.x);
   }
}

When I enter play mode, the property resets.
I tried fixing it by adding:
if(GUI.changed) EditorUtility.SetDirty(a);

However this only fixed it for play mode.
If I save and close the scene, it resets to the default.
Also, the scene is not set to dirty, if I make changes to the component through the custom editor.

You'll notice the docs for SetDirty point out that this method has been replaced:

Prior to Unity 5.3, this was the primary method of marking objects as
  dirty. From 5.3 onwards, with the introduction of Multi-Scene Editing,
  this function should no-longer be used for modifying objects in
  scenes. Instead, you should use Undo.RecordObject prior to making
  changes to the object. This will mark the object's scene as dirty and
  provide an undo entry in the editor.

Here's how your code would look with this pattern:
public override void OnInspectorGUI() {
    A a= target as A;

    if (a== null || a.gameObject == null)
         return;

    EditorGUI.BeginChangeCheck();
    bool x = !EditorGUILayout.Toggle("x", !a.x);
    if(EditorGUI.EndChangeCheck()) {
        Undo.RecordObject(target, "Changed x");
        a.x = x;
    }
}

Ah...thanks! I already changed my editor scripts to use serializedObject.FindProperty("myProperty");, EditorGUILayout.PropertyField(myProperty, new GUIContent("My Property")); and serializedObject.ApplyModifiedProperties();.

Feel free to add that as another answer, as it's also a completely valid way to handle serialization.

Here's another solution that I ultimately went with:
[CustomEditor(typeof(A))]
public class A_E: Editor
{
   private SerializedProperty x;

   public OnEnable(){
      x = serializedObject.FindProperty("x");
   }

   public override void OnInspectorGUI()
   {
      serializedObject.Update();
      x.boolValue = !EditorGUILayout.Toggle("x", !x.boolValue);
      serializedObject.ApplyModifiedProperties();
    }
}


text:
I have a Unity addon that generates noise via a shader. How can I use it besides just dragging it onto a mesh?
I'm probably asking this question wrong. I'm using Turbulence Library to generate noise as shaders. What I want to do is take the noise generated by these shaders and apply them to Texture2Ds that I'm procedurally generating.
What I want to do is take the value of each pixel from the noise, then while procedurally generating a texture, use to determine how much I put another color "on top of" another color in a procedurally generated mesh. I would post an example picture, but I can't do that since I can only post one link with my reputation.
I strongly suspect that I will just have to write my own shader from scratch, but is there no way to just take noise from a shader and apply it to a Texture2D so I can continue to use the Standard shader?

Why do you say there's no way to take noise from a shader and apply it to a texture? That's effectively what the rendering pipeline does every time it writes shader output to the frame buffer. All you need to do is capture that output into a RenderTexture of your choosing instead of the frame buffer, using a camera with a target texture set or Graphics.Blit — have you tried either of these avenues?

I've never heard of RenderTextures before. Will they basically let me get a bitmap out of a Shader while still in C#? Because that's pretty much all I need.
Hell, I have the pictures I was talking about here: http://answers.unity3d.com/questions/1409480/how-do-i-get-the-noise-from-a-shader-generated-fro.html

You don't even strictly need the C#, you could do it entirely with asset/scene/inspector setup if you so chose. I don't see any obstacles to what you're describing.

I'm not really sure how to do this. I don't actually have access to Unity for another two hours, but the problem basically boils down to "I don't know what to drag it over in the Inspector" and "I don't know how to use a shader like Mathf.PerlinNoise"

I think Custom Render Textures is what you need: you can fill it with your own shader, use parameters from materials, assign it to texture slots (like a normal Texture2D), etc.


text:
Running a C# Function in Unity with a button press
Heads up - I'm not very experienced with Unity, and haven't coded in C# before. (I have some experience in Python)
I'm trying to create an app that requires small packets to be sent from a smartphone to a Raspberry Pi.  In order to do this, I'm using OSC - or Open Sound Control.  I have the Raspberry Pi setup to listen for messages, just having trouble with Unity.
I'm using UnityOSC (there's two of them)
Github: https://github.com/thomasfredericks/UnityOSC
Documentation: http://thomasfredericks.github.io/UnityOSC/
I'm trying to send a packet of data whenever a button is pressed (and each button needs to send a different packet to identify which button has been pressed).  I don't know how I can create a script that is activated with a button press.
Is there a way to make one script with a function that takes the button name as a parameter and then send that?
Thanks for the help, and if you need more information, please ask!  Again - I don't have experience with this and I would appreciate a "lower experience level" explination.  Thanks!

Yes, the visuals are done - just trying to run a script when they are pressed

Create a script with a public void method which does what you want.
Put that script on a game object in your scene which is always present. This can be the button itself, if you want, but can also be any other game object which is part of the scene from the start.
Select the button
Click the plus-button in the On Click () panel of the Button's inspector (image 1)
Drag the game object with the script onto the slot which reads None (Object) (image 2)
Select the method from your script (image 3)

Image 1:

Image 2:

Image 3:

Is there a way to use the button name as an input to the function?

@CMalasadas AFAIK not directly. But when you put the game object onto the button itself, you can get the name of the current game object with gameObject.name. But usually I would rather create a separate method for each button.

I'm having trouble calling up my public void function - I can't find it listed in unity under the function dropdown.


text:
How to make community made levels compatible with every game update, without re-cooking the levels?
Community made maps made in UE4 (BSP & simple assets), downloadable via Steam Workshop, is one of the main features of our hypothetical game. The maps should continue to be compatible regardless of game-updates, without re-cooking each map. Is this possible? Because now it seems every map has to be re-cooked after every game update. However, our hypothetical game can't work like that, considering it has to work with hundreds of community made maps which we can't expect users to re-cook every time.

What do you mean by "re-cooking" exactly? This affects possible answers a lot.

Well, the need for the author to open up his level in the editor and rebuild it again after there was an update to the game. It comes down to the following: community made levels should forever be compatible with any game update, without having to update the level in any way.

You need to outline the meaning of "any" game update as well. E.g. if you introduce brand new wall-climbing class, certainly level geometry should be re-evaluated.

Any update that doesn't require a re-evaluation of the level. Let's say there is a game called X, version 1.0, and users have created 100 levels. Then update 1.1 comes along; all the levels should still work (assuming there is no change in movement that requires all levels to be changed).
Sorry for lacking specifics. A friend and I are just brainstorming about a game and we want this possible problem addressed before we start anything.

Problem lies in defining a contract between the game and the levels. If game 1.1 changes the contract - all levels must be reevaluated. If the contract remains the same - no change is needed.


text:
Shaders vs renderers: Photorealism
What is Renderer? How it is different from a shader?
For Photorealism which one is more important?

This post appears to be two distinct questions. Please only include one question per post.

Shaders and renderers are two different things. A renderer is simply a piece of code written on top of a rendering API (such as OpenGL or DirectX) and it handles the model rendering (hence the name).
A shader is also a piece of code, but it runs on the GPU. It's optimized to work on hundreds of threads at once and it's usually used to figure out the position of a vertex (a point of a 3d model) relative to the camera (vertex shader) or to figure out the color of a certain pixel (fragment shader).
Your third question makes no sense currently. None of them are required to achieve photorealism. You can make photorealistic images with just shaders (like here) and you can also achieve it without using a shader, in fact, ray tracing is the current standard in movie making and it doesn't have to involve the usage of shaders.

I would argue that even the ShaderToy example has a very simple renderer in play, providing the viewport and quad geometry with UV coordinates to be shaded, and piping in variables like texture sources or user input. ;) And a raytracing renderer is still a renderer, it's just a fundamentally different way of implementing responsibility for generating an image.

@DMGregory 1.) Fair point 2.) Thanks for mentioning, that should've been the renderer only one, I'll fix it


text:
How to render a model that consists of individually transformable parts?
Consider a 3D model for a spider that consists of a body and eight legs. The legs can be transformed (rotated) relative to the body. I am not sure what the common ways of rendering such a scene are, at a low level. Two ways I could think of:

Render the body and legs separately, using different VBOs (or different indices) (one for the body, one for the leg) and separate draw calls.
Encode in each vertex which body part it belongs to, and decide based on this information how to transform the vertex in the vertex shader.

I searched a bit and could find some tutorials on skeletal animation and similar techniques, but they still boil down to this question.

Not really sure what you are asking. Are you referring to animation

@unknownSPY Not necessarily animation. It seems to me that drawing the whole model in one go is not possible to do in a sane way, but I might be missing something. So the question is: do I have to render the different parts of the model separately?

Your second guess is almost correct. Skeletal based animation usually uses a weight map to bind certain vertices to certain bones (a single vertex can have multiple parent bones, there's usually an upper limit though). Then a vertex shader is used to move the vertices based on their parent bones.
Basically, the files include the skinning values for the separate bones, you process them and send them to the shader somehow. I've seen people using a vec4 and 4 matrices to store the transformations to do this, which limited the weights per vertex to 4 (you usually don't have much more), but it's up to the programmer to decide how he does it.
You can still do the same if you don't want to use this for animation, but instead of using bones, just use a pseudo element with a position and an id

It might be good to include a bit more details about how this type of GPU skinning is achieved - eg. how the vertex shader gets access to bone transforms - since it seems like this user is looking for low-level implementation information like VBO setup.

@DMGregory I'll try

If I understand this correctly, each vertex would contain along with the position a weight value for each bone. Then it’s a matter of multiplying the position by the weighted sum of the bones given the weights.

@DMGregory I gave an example, but it's really up to the programmer to decide

I think skeletal animation is only really possible if you have the bones set up and have the animation frames available. If you have all of that, the skeletal is the way to follow.
If you do not, then I would go forward with your first option, but set it up as a scene graph, to learn about scene graphs I would take a look at this info on scene graphs


text:
WinAPi OpenGL Borderless Fullscreen - Alt Tab problems
I'm implementing a borderless fullscreen functionality and managed to make something that almost works. Using: C++, Winapi, OpenGL 3.3.
When  in fullscreen borderless mode, if alt tab the game window loses focus but is still on top, not even the alt tab window shows.
I managed to track it down to SwapBuffers. If i disable it, no problems but also no rendering.
If i force the window to hide when it loses focus, the entire screen flickers. And if i alt tab back, only the game window flickers.
If i put the game in windowed mode, it works as normal.
Window Styles are first set to(windowed mode stops  here):
WS_OVERLAPPED | WS_MINIMIZEBOX | WS_SYSMENU | WS_VISIBLE

And then are set to(if fullscreen):
GetWindowLong(window, GWL_STYLE) & ~WS_OVERLAPPEDWINDOW

My gameloop:
while(isRunning)
{
    loopNewTime = timeGetTime();
    loopDuration = (r32)(loopNewTime - loopOldTime);
    loopTime = Clamp(0.0f, (loopDuration - sleepTime), 250.0f);

    loopOldTime = loopNewTime;
    loopAccumulator += loopTime + sleepTime;

    while(loopAccumulator >= loopFixedDeltaTime)
    {
        if(isFocused || canRunWithoutFocus)
        {
            DoStuff();
        }

        loopAccumulator -= loopFixedDeltaTime;
    }

    if(isFocused || canRunWithoutFocus)
    {
        DoStuff();

        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

        DrawStuff();

        SwapBuffers(deviceContext);
    }

    framerateTimeThreshhold += loopTime + sleepTime;
    ++framerateCount;

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

    sleepTime = Max(timeStep - loopTime, 0.0f);

    Sleep((u32)sleepTime);
}

So, how can i solve this problem?
Thanks in advance.

To anyone with this problem, i found a 99% perfect answer here: https://stackoverflow.com/questions/23145217/flickering-when-borderless-window-and-desktop-dimensions-are-the-same
What i did: Set the window size to the size of the screen + 1. For some reason if window and screen are the same size, Windows reacts like a normal fullscreen.

Post that as an answer

If you take away WS_OVERLAPPEDWINDOW maybe there's no style left - have you tried setting the WS_POPUP style? SetWindowLong(window, GWL_STYLE, (GetWindowLong(window, GWL_STYLE) & ~WS_OVERLAPPEDWINDOW) | WS_POPUP);

To anyone with this problem, i found a 99% perfect answer here: https://stackoverflow.com/questions/23145217/flickering-when-borderless-window-and-desktop-dimensions-are-the-same
What i did: Set the window size to the size of the screen + 1. For some reason if the window and the screen are the same size Windows will act like it's a "normal" fullscreen.


text:
How to improve my input handling in GLFW?
Currently I'm busy working on a game engine. I have my own window class with GLFW functionalities. Currently, I have a very primitive way to handle input in my class:
It is not fast, and not "extendable" enough. I'm essentially using something along the lines of
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_E && action == GLFW_PRESS)
        //do something
}

I would like to call something like the following:
// Create a window object
Window window("title",800,600);
//the parameters specify the key pressed and what the window has to do when the event occurs.
window.getKeyPressed(KEY,ACTION);

How would I go about implementing a more flexible input handling system?

It's a little unclear what you want here? A specific function to be called when the E-key is pressed instead of a generic one?

Yes, not the E key in particular, a general key. I also wanted to know what is the "best way" possible to handle input using Glfw in an ipothetical Window class

Best way is subjective.

I understand, but i actually wanted to have a cleverer method to handle input since mine is not good. That's all

If if-statements won't do it for you, I'd suggest a map-based approach, where your Window (or a separate InputManager) class stores a map of function callbacks, that get invoked when a key is pressed.
class Window
{
public:
    using Callback = std::function<void()>;

    void addBinding(int key, const Callback& callback)
    {
        m_Callbacks[key].push_back(callback);
    }

    void onKeyPress(int key)
    {
        for (Callback& callback : m_Callbacks[key])
        {
            callback();
        }
    }
private:
    std::map<int, std::vector<Callback>> m_Callbacks;
};

This way you can create std::functions and pass those to the class, and then once you get a keypress event from GLFW, all you have to do is call onKeyPress with the correct key, and the callbacks will get invoked.
Just be careful with object lifetime if you end up creating std::functions for class methods. Adding a removeBinding method to the Window class might not be a bad idea.
Also, supporting other events (like key releases for an example) isn't tricky at all with this solution: either add a specific method (like addReleaseCallback) or introduce another layer to the map, so that the first layer fetches the correct bindings for an event type, and the second layer is the key lookup.

Thank you for helping, i will definitely try to implement this into my engine!

Similar to Tyyppi_77's answer, I also normally opt for a map-based approach. However, I prefer to use a map similar to the one shown below:
struct KeyPress {
    bool current, previous;
}

std::map<int, KeyPress> mKeyPresses;

This way, you can track whether the key has just been pressed, released, or is being held down, based on combinations of bools. You can also easily specify which keys are used, without having to track all of the keys or rely on complicated callbacks. It also, in my opinion, makes conditional events easier to control over callbacks, because you can use if/switch statements to handle whether a key is in a certain state or not.

There is another option, which is more object orientated.
Generate an engine input event for each GLFW input and send it to a central event queue. Then you can have a bunch of behaviours elsewhere in your engine that will handle respond to these events via hard coded behaviour, or scripts:
class KeyEvent : public GameEvent {
    public:
        int key;
        int keystate;
};

handleInput(GLFWwindow* window, int scancode, int keystate, Engine& engine) {
    auto event = std::make_shared<KeyEvent>();
    event->key = scancode;
    event->keystate = keystate;
    engine.enqueueEvent(event);
}

Your handler would look something like:

class Controlhandler {
    //game state stuff here
    public:
        void handleEvent(std::shared_ptr<GameEvent> event) {
            auto e = std::dynamic_ptr_cast<KeyEvent>(event);
            if(e){
            // check event, update state, and respond.
            }
        }
};

In this way, you can write control handlers which do a bunch of different stuff with the same events.


text:
Weird streching of a texture in OpenGL
Here is the problem: I'm rendering a red triangle in an offscreen Frame Buffer Object. I have a texture of that Buffer, and i'm applying this texture to a Simple rectangle(at runtime).
I get This result:

This is exactly what i wanted. the problem is that when i strech my window the texture gets a little weird:

Just for curiosity i tried to render the rectangle without the texture.

And then I stretched the window once again:

I believe this is happening because in my default FBO I am setting glViewport to glViewport(0,0,m_Width,m_Height); (m_Width and m_Height are the dimensions of the Window)

I forgot to say i am using glfw as the windowing api. About glViewport, i am setting it every frame. Maybe this happens because i don't have a projection matrix of any sort..

if you don't have projection matrix, it defaults to -1 to 1 and your rectangle, of course, automatically follow that if you didn't update the rectangle coordinates.

Your guess is correct. Every time you resize your window, make sure both of your glViewport() and projection matrix are up to date. In SFML it would be something like this:
while (running) {
    sf::Event e;
    while (wind.pollEvent(e)) {
        switch (e.type) {
        // ...
        case sf::Event::Resized:
            glViewport(0, 0, e.size.width, e.size.height);

            // Set your projection matrix here
            // Will be different from one library to the other

            break;
        // ...
    }
    // ...
}


text:
Render in a imGui Window
How do i render my game scene into an imgui window?
I want to get from this:

to this :

First of all we need to create what is called Frame Buffer Object, or FBO for short. I'll leave you a great tutorial on (pretty much everything regarding OpenGL)FBOs right here: https://learnopengl.com/#!Advanced-OpenGL/Framebuffers
Now that we created an FBO, we should have a texture. This texture contains the image of what is rendered on the FBO. At this point all we need to do is to "put" this image inside of a dear ImGui Window. Let's see how to do this:
//this is our main game loop
while (!window.Closed())
{
    //we need to clear the window,
    //This is how the clear method is structured:
    //void Window::Clear(float x, float y, float z, bool enableGLDepth,bool clearImGUIframe)const
    //{
    //  //clear the color of the window with an alpha value of 1.0f
    //  glClearColor(x, y, z, 1.0f);
    //  if (clearImGUIframe)
    //  {
    //      ImGui_ImplGlfwGL3_NewFrame();
    //  }
    //  if (enableGLDepth)
    //  {
    //      //enable the GL_DEPTH_TEST to be able to see 3D object correctly
    //      glEnable(GL_DEPTH_TEST);
    //      //clear both the color buffer bit and the depth buffer bit
    //      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //  }
    //  else
    //  {
    //      //clear just the color buffer bit
    //      glClear(GL_COLOR_BUFFER_BIT);
    //  }
    //}

    window.Clear(0.5f, 0.5f, 0.5f,true,true);

    //switch to our custom FBO
    //window.bindFBO is the same as writing glBindFramebuffer(GL_FRAMEBUFFER,FBO);
    window.bindFBO();

    //we need to call clear twice
    window.Clear(1.0f, 1.0f, 1.0f, true, false);
    //Draw our simple triangle
    shader.Use();
    glBindVertexArray(Tvao);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    //switch to the default FBO
    //again, unbindFBO() is the same as glBindFramebuffer(GL_FRAMEBUFFER,0)
    window.unbindFBO();

    //create our ImGui window
    ImGui::Begin("Scene Window");
    //get the mouse position
    ImVec2 pos = ImGui::GetCursorScreenPos();

    //pass the texture of the FBO
    //window.getRenderTexture() is the texture of the FBO
    //the next parameter is the upper left corner for the uvs to be applied at
    //the third parameter is the lower right corner
    //the last two parameters are the UVs
    //they have to be flipped (normally they would be (0,0);(1,1)
    ImGui::GetWindowDrawList()->AddImage(
        (void *)window.getRenderTexture(),
ImVec2(ImGui::GetCursorScreenPos()),
        ImVec2(ImGui::GetCursorScreenPos().x + window.getWidth()/2,
ImGui::GetCursorScreenPos().y + window.getHeight()/2), ImVec2(0, 1), ImVec2(1, 0));

    //we are done working with this window
    ImGui::End();
    //swap the buffers and check for events
    window.Update();
}

after all this you should get this result:

Hope this helped someone! I'll also leave the entire code i am using down here:
Main.cpp
#include "Engine.h"

using namespace Engine;
using namespace graphics;

int main()
{
    Window window("Advent3D", 800,600, false);
    Shader shader("Res/Shaders/Unlit.shader");

    //TRIANGLE CREATION//
    float Tvertices[] = {-0.5f, -0.5f, 0.0f,0.5f, -0.5f, 0.0f,0.0f,  0.5f, 0.0f};

    unsigned int Tvbo, Tvao;
    glGenVertexArrays(1, &Tvao);
    glGenBuffers(1, &Tvbo);
    glBindVertexArray(Tvao);
    glBindBuffer(GL_ARRAY_BUFFER, Tvbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Tvertices), Tvertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);

    while (!window.Closed())
    {
        //we need to clear the window,
        window.Clear(0.5f, 0.5f, 0.5f,true,true);

        //switch to the custom fbo
        window.bindFBO();

        window.Clear(1.0f, 1.0f, 1.0f, true, false);

        shader.Use();
        glBindVertexArray(Tvao);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        //switch to the default fbo
        window.unbindFBO();

        ImGui::Begin("Scene Window");

        ImVec2 pos = ImGui::GetCursorScreenPos();

        ImGui::GetWindowDrawList()->AddImage(
            (void *)window.getRenderTexture(), ImVec2(ImGui::GetCursorScreenPos()),
            ImVec2(ImGui::GetCursorScreenPos().x + window.getWidth()/2, ImGui::GetCursorScreenPos().y + window.getHeight()/2), ImVec2(0, 1), ImVec2(1, 0));

        ImGui::End();

        window.Update();
    }
}

A gist would be greatly helpful for newcomers. A simple 3D cube in an imgui window.

The best approach I found so far that integrates well with windows even if they hover above others (in contrast to the original answer) and is also performant when rendering multiple views (in contrast to the accepted answer of using images), is as follows:
int fbX, fbY;
glfwGetFramebufferSize(ImGui::GetCurrentWindowRead(), &fbX, &fbY);

auto viewWin = ImGui::GetCurrentWindowRead();
Eigen::Vector4f viewRect(viewWin->InnerRect.Min.x, viewWin->InnerRect.Min.y, viewWin->InnerRect.GetWidth(), viewWin->InnerRect.GetHeight());
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddCallback([&](const ImDrawList* dl, const ImDrawCmd* dc)
{
    Eigen::Vector4f clip(
        dc->ClipRect.x, dc->ClipRect.y,
        (dc->ClipRect.z-dc->ClipRect.x), (dc->ClipRect.w-dc->ClipRect.y));
    viewRect *= pixelRatio;
    clip *= pixelRatio;
    glViewport(viewRect.x(), fbY-viewRect.y()-viewRect.w(), viewRect.z(), viewRect.w());
    glScissor(clip.x(), fbY-clip.y()-clip.w(), clip.z(), clip.w());
    glClearColor(0.2f, 0.0, 0.2f, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Enable Depth for 3D scene
    glDepthMask(GL_TRUE);
    glClearDepth(0);
    glDepthFunc(GL_GEQUAL);
    glEnable(GL_DEPTH_TEST);

    // TODO: Render 3D scene
}, nullptr);
draw_list->AddCallback(ImDrawCallback_ResetRenderState, nullptr);

The example uses glfw and some eigen but the idea should be clear. Use a callback to render a scene (3D or not) at the right time so the UI elements that should be behind are behind, and the ones ontop are properly ontop. UI is always rendered ontop, so no need to worry about depth buffer, you can use it for your scene or not.
The advantage is also that it'll only render the part of the scene that is visible, and you can differentiate between your viewRect and your clipRect.
Original Answer:
A much simpler (and, if you have multiple windows with GL viewports, more performant) solution, is to keep all background of windows with GL ports transparent (and dockspace background, if you use it), and then manually clear the backgrounds (using glViewport and glScissor followed by glClearColor and glClear) using the rectangle of each window (GetWindowPos/GetWindowSize).
Then you can first render your GL part using the same method in the rectangles you want them to be in, and then the UI on top. Looks seamless, and should be much more performant than multiple render passes.

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


text:
How do I prevent modders from creating malicious code?
Let's say I have both a game and a modding system for it. The modding system loads DLL files containing custom features and allows mod creators to override certain functions to change game mechanics. This is all well and good until some mod creator decides to put a keylogger or a virus in one of those DLL files. What can be done to prevent this problem? Is there any way to allow a high level of customisability in a modding system while still maintaining a strong level of security for the end user?

Is taking the mods in DLL format a requirement? Or would you be open to exposing your modding functionality in other ways that don't necessarily entail running arbitrary native code?

@DMGregory How else could you do this?

That's s job for an answer, but as just one example, you could load a text or bytecode script file that's run in a virtual machine inside your game, with access to only the methods you want to expose, so you can have a strong guarantee that it's not making arbitrary system calls or vandalizing the player's machine.

@Gigas I would argue that how else you might do it is a related, but separate question. I totally agree that there are other, possibly better (or at least more secure) alternatives. If that's what you want, I encourage you to ask a new question.

@Pikalek The question is about how to prevent, so how else you do it definitely is within the scope of that question. The question itself doesn't specify that you need to use dll files, just that OP is doing that now. recommend against separation of the questions.

Actually, as i'm thinking about it, this question boils down to "how else should I do it?" Imo

You cannot prevent it (in situations which are equivalent to running arbitrary native code supplied by others).
You can:

curate the mods
screen submissions with a scanner
restrict your API as much as possible
select a language that is safety oriented
sandbox foreign code

All of these increase safety to varying degrees.
But none of them are a guarantee.

Is there any way to curate DLL files if the source code of the mod is not provided?

By curate, I was referring to a generic process by which files (of any type) are submitted for review & only made available upon approval. In that sense, you can curate most anything. The logistics of implementing such a plan vary. for instance, the approval process may be simple (ran it & it didn't crash) or complex (examining the binary for suspicious instructions).

With DLL files, points 3-4 are impossible and 5 is very difficult. DLL files contain compiled binary code. A DLL can do anything a windows executable can, include calling native windows API functionality. And they don't need to be written in the same programming language as the program which calls them.

True, you cannot control the language selected by the user or the API provided by the OS. API restriction & language choice can make your own program more resistant to exploit by removing a few easy attack vectors. I'm not up on modern OS memory management to know if something like a buffer overflow in the DLL can be exploited by the DLL to access the memory space of the calling app, though.

As others have stated in the comments, the easiest way is to either embed an interpreter in your game (for example, Lua scripts are fast-ish, and there are a number of good implementations scattered across the web for various languages) or create a simple text parser and read files. For example, you could roll your own text format for simple scripts, embed lua for mire complex scripts and gui-related tasks, and load object definitions from JSON or XML.
For example, in my strategy game;
1.) Unit types are defined in xml - safe[1].
2.) GUI layout is defined in xml - safe.
3.) I use a custom parsed scripting language for simple events.
4.) Lua is used for gui interaction. I have removed the io, and os functions effectively rendering these scripts safe.
[1] - As others have stated, these approaches aren't necessarily "safe" just "safer" than including compiled dll's.

While those approaches seem safe if implemented correctly, you need to be weary of implementation errors. Programming languages like C/C++ without automatic bounds checking make it very easy to build bugs into parsers which allow arbitrary code execution. And disabling functionality in a programming language can be harder than it seems at first glance, as numerous vulnerabilities in the Java Applet technology for web browsers have shown in the past.

I think "safe" always needs an asterisk. For instance, I could make a mistake in my XML parser logic that, say, assumes a text string won't be longer than X, or doesn't sanitize it for escape characters, leaving it vulnerable to a buffer overrun or "Bobby Tables" attack, where "safe" xml might be able to trigger behaviours I didn't deliberately expose. ;)  Ooops, looks like Philipp and I were typing the same thing at the same time! Sorry for the double-up!

@Philipp Fair enough, I've edited the question slightly, though the xml approach is almost undoubtedly safer than including potentially-malicious native code :-)


text:
Convert char array to std::string
I have this code:
char shaderName[128] = "";//the name of the file
char text[1024 * 16] = "";//the content of the file
std::ofstream myfile;//the file
myfile.open(shaderName + ".shader");//i want to concatenate the file name with the .shader extension
myfile << text;//put the content of the text array in the file
myfile.close();//close the file

This gives me an error. It tells me i can't convert a char array to a string or const char*. I want to be able to concatenate the nameof the file with the .shader extension. I also tried to cast shaderName to an (std::string) or a const char*
EDIT:
ImGui::Begin("Shader Writer");

char text[1024 * 16] = {""};

char shaderName[128] = {""};

ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetWindowHeight()), ImGuiInputTextFlags_AllowTabInput | (false ? ImGuiInputTextFlags_ReadOnly : 0));

    ImGui::Text("Shader Name: ");
    ImGui::InputText("", shaderName, IM_ARRAYSIZE(shaderName));

    ImGui::SameLine(0.0f, 2.0f);

    if(ImGui::Button("Create", ImVec2(50, 20)))
    {
        char shaderName[128] = "";

        std::ofstream myfile;

        std::string name(shaderName);
        std::string FileName = name + ".shader";

        myfile.open(FileName.c_str());
        myfile << text;
        myfile.close();
    }

    ImGui::End();

The InputTextMultiline() function let's you modify,write,read a text. The "text" in this case is a char array(this function outputs a char array).
Then we have another InputTextMultiline() function which also returns a char array. In order to use this data returned by these functions, i need to convert them to strings(or maybe to const char*,even tho i think std::strings is better).
Here is a rapresentation of what these functions do:

Your edit doesn't say what your new error is?

But your declaration of "shaderName" inside the if() is suspicious as it hides the outer variable that you presumably filled using the InputText line.

Yes, i corrected it in the actual code but not in the question. I apologize for that

This gives me an error. It tells me I can't convert a char array to a string or const char*. I want to be able to concatenate the name of the file with the .shader extension. I also tried to cast shaderName to an (std::string) or a const char*.

You can't concatenate C-style strings using +. If you want to use operator+ you'll have to use std::string. Otherwise you'll have to use strcat().
std::string shaderName = "";
...
std::ofstream myfile;
myfile.open(shadername + ".shader");
...

Note that open() does not accept std::string until C++11; prior to that you'll need to concatenate the name into a local variable and use c_str():
std::string fileName = shadername + ".shader";
...
myfile.open(fileName.c_str());

If you must use strcat instead:
char shaderName[128] = "";
strcat(shaderName, ".shader");
myfile.open(shaderName);

It is your responsibility to ensure shaderName is large enough to hold the resulting buffer.


text:
Infinite loop ping test for each player
For my Unity game I have a Client-Server model, and I want both sides to ping each other repeatedly to make sure I know what latency between players is.  In the server's case, a client connects and their details are logged.  Their details are then used when the game creates coroutines. This coroutine starts a loop which pings and waits and pings and waits, etc, until the game ends.
However, it doesn't work.  The debug messages are throwing up strange results.   It attempts to ping to IP "::ffff:192.168.0.10", and then is waiting forever.  I don't suppose the fact I am running this via Unity editor and another app window on the same machine should be an issue?  What is the "::ffff" about in the IP it saves when a client connects?  Is that the issue?  If so, how can I best format it properly?
Yes, I need to add another loop in the coroutine to make it go forever.  Once would be a nice start though.
CLIENT CONNECTS TO SERVER
    // Recieve data from all.
    NetworkEventType recData = NetworkTransport.Receive(out socketId, out connectionId, out channelId, buffer, bufferSize, out dataSize, out error);

    switch (recData)
    {
        case NetworkEventType.ConnectEvent:
            if (localConnectionId == connectionId)
            {
                // My active connect request approved.
                Debug.Log("Connection request approved.");
            }
            else // New client.
            {
                string outIp;
                int outPort;
                UnityEngine.Networking.Types.NetworkID outNetwork;
                UnityEngine.Networking.Types.NodeID dstNode;
                byte outError;
                NetworkTransport.GetConnectionInfo(socketId, connectionId, out outIp, out outPort, out outNetwork, out dstNode, out outError);
                AllocateNewLobbyPlayer(socketId, connectionId, channelId, outIp, outPort);
            }
            break;
   }

CREATE PING LOOP COROUTINES
    for (int i = (Game.isServer) ? 1 : 0; i < lobbyPlayers.Length; i++)
    {
        if (lobbyPlayers[i] != null)
        {
            Debug.Log(" STARTED PING FOR " + i);
            StartCoroutine(PingTest(lobbyPlayers[i].ip));
        }
    }

PING LOOP COROUTINE
protected IEnumerator PingTest(string ip)
{
    Ping ping = new Ping(ip);
    Debug.Log(" SENT PING " + ip);
    while (!ping.isDone)
    {
        Debug.Log("WAITING");
        yield return new WaitForFixedUpdate();
    }
    Debug.Log(" PING COMPLETED " + ping.time);
    yield return new WaitForFixedUpdate();
}

DEBUG OUTPUT
 STARTED PING FOR 1
 SENT PING ::ffff:192.168.0.10
 WAITING
 WAITING
 WAITING

etc, etc, etc...

"::ffff:192.168.0.10" that's a transitional IPv6 address. Can you open up a command prompt and ping 192.168.0.10?

@Jimmy I can't test that right now (though I will soon) but is this to say you can't see anything else wrong?  Or that this just the most obvious problem?

I suspect a regular ping will timeout as well, so this would be the next thing I test. I imagine the address formatting is not really issue.

@Jimmy Turns out, it was.  Removed ::ffff: from string and worked perfectly.  Admittedly I changed the ping class code a bit but the problem was basically it mapping a ipv4 to pseudo ipv6 prefix or something. Need to be just ipv4 format.

glad you got it worked out! You should write up your results in an answer for future readers.

Ping is implemented differently on different platforms.
On some platforms, it's an ICMP Echo Request (the thing that happens when you enter ping [ip-address] in your command shell). These might be blocked by firewalls or routers which do not block the normal game traffic. On others it tries to open a HTTP connection to port 80, which of course doesn't do much if the target IP does not run a webserver.
If what you actually want to do is check the quality of the game connection, you are better off implementing your own Ping message as part of your game's network protocol.

When you say implementing your own solution, in Unity's case, would this be, say, sending a simple object on a unique connection channel, which logs the round trip time?  Since that's basically what is necessary, just always knowing what the current ping time is?

To add to @Philipp answer,
don't forget that there is NetworkTransport.GetCurrentRTT() that allows you to get milliseconds that it takes to travel to destination and back. Notice, you have to be already connected for this to work.


text:
What is the little dot/icon at the center of the screen in an FPS game called?
So I am developing a game and trying to find one of those to use, but I don't know what to search for. If you don't know what I am taking about, look at these examples:

What are these called?

Someone protected this so I can't post an answer. But an older term that refers specifically to dots on gunsights is Tommy Dot. This probably won't help you though, because I doubt many video game designers use the term.

Why was this protected? It feels a little odd that the presence of a single mediocre answer was enough to protect a question...

The pew pew hole

"Crosshairs" or an "aiming reticle," usually. Probably also "aiming dot" and similar variations.

Also spelled "reticule" (which, by delightful coincidence, also means a small ladies' handbag).

I've also seen the term "boresight" used for this

Also "targeting reticle".

I'm used to use 'crosshair' myself. But didn't knew that it's actually a subterm of the 'reticle'. interesting to know.

In addition to what Josh Petrie mentioned: if you're looking for more advanced ways to aim weapons, the center dot in your bottom image is also called a "pipper" in real-life applications.
This especially applies when some device is actively predicting where an arcing projectile will impact, like a bomb or grenade, instead of simply showing which direction it will go when fired/thrown/dropped.
Aircraft HUDs combine pippers and reticles to convey extra information about complicated firing solutions, as shown in this example:

Continuously Computed Impact Point Reticle
So in your third image, the circular arcs are the reticle, while the center dot is the pipper.

That's usually called a crosshair. Also they're probably the easiest texture to make yourself, you don't need to find one online.

This adds nothing to the answers already posted.

It's simpler. Some of the other answers contained more information than requested, which could be confusing to readers. This answer only answers the question directly.

Please tell me how you answer is simpler than Josh Petrie's answer? It even contains more characters.

@Charanor It provides only one, most common, answer instead of two alternatives with speculation and an unnecessary link.

This is a place to come to be informed. Dumbing down answers to provide one interpretation of what you believe to be the "better" answer completely misses the point.

... and if one is confused by the fact that more than one term exists that refers to the same thing, and the presence of a link, I'd imagine that person would have a couple more important issues to worry about.

"You don't need to find one online" is also very subjective.
A basic, pixelated sprite is easy indeed. but making any of the HQ recticles can't be done with your basic paint program.


text:
How to compute the area of an irregular shape?
I have a room object defined by a collection of looping line segments that I need to calculate the area for. The classes can be described as follows (in pseudo-code):
class Point {
    float x;
    float y;
    ...
    float distanceFrom(Point p);
}

class Segment {
    Point start;
    Point end;
    ...
    float length();
}

class Room {
    List<Segment> walls;
    ...
    float area();
}

The walls of a room can never intersect anywhere but at the endpoints of the segments and any "sub-loops" created will also be separated into a new room. The solution does not need to be perfectly accurate (10% margin of error is acceptable) and is also not computed very often (<1/s).

It would make more sense for Room to contain a list of Points, and then get the segments by connecting each point together and then loop it back around. Otherwise, with your current setup, it's very east to get incorrect values (e.g. unclosed room, room with wall in middle, etc.). This would be the best option.

Another option is top triangulate the shape and calculate the areas of each triangle. The hard part is the triangulation. Doable, but not always pretty. The shoelace answer is still way better.

@MCMastery That solution won't work, as it requires Rooms to always be complete, and that may not be the case if I have the player build the Rooms using Segments. Also, a closed-room function is easy to define (just loop through the Segments and make sure they create a room).

You can use Gauss' shoelace formula:
You need to take the x coordinate of every point, multiply them by the next point's y coordinate, then subtract the current point's y coordinate multiplied by the next point's x coordinate from the result and add them to the total area. After you did this for every point, halve the total area to get the actual area of the polygon. If the current point's the last one, then the next is the first.
A = 0

for (i = 0; i < points.length; i++) do

    A += points[i].x * points[(i + 1) % points.length].y - points[i].y * points[(i + 1) % points.length].x

end

A /= 2

I always used that to calculate the cross product of two vectors never knew it was called shoelace algorithm

Note that this can be extended to compute the volume of an irregular 3D object made of triangles, and it can be considered a trivial case of the fundamental theorem of calculus.

The area here is signed.  Go through the points in the other direction and the final A is negated.  Depending on goal, a A = |A| may be needed.  With negative area code can find the area on an irregular donut using the inside and outside list of points (one in the opposite order).

Because of course either Gauss or Euler has a formula for it.

We could also use a Monte Carlo method.

Draw a rectangle around the arbitrary shape. Take a uniformly distributted PRNG source eg. mersenne twister, then bound the output by rectangle's X,Y lengths using modulo function. Count the no. of random-points that land inside your shape. Divide by the total amount of points generated. Multiply that quotient by the rectangle's area. With each iteration you will converge to the true area.

The algorithm is ridiculously parrallelizable and can used to calculate arbitrary dimensional shape 'volumes', as long as you can determine if an R^N coordinate falls within shape's R^N boundary.

.

Here someone is using this method find circle area then uses that to calculate pi https://www.youtube.com/watch?v=VJTFfIqO4TU

-1: You don't want to be using modulo to get it in range, you want to use a uniform distribution or other distribution, doing it the modulo way has all sorts of statistical issues.

This method might be beneficial when we don't have a simple polygon, but rather some kind of implicit shape whose border is difficult to express, like a fractal or metaball blob. For the case of a polygon as in the question though, it seems like it would be needlessly expensive.

As @DMGregory pointed out, this is not what I was looking for. However, I think it deserves a +1 in case someone else needs it.

This is interesting but wouldn't the cost of the inclusion tests get prohibitive? I.e. if you have a shape that is sufficiently complex to warrant this approach, wouldn't the inclusion tests also be really expensive so you wouldn't want to do tons of them? (assuming polygons)

Ok  modulo is indeed problematic, but it's a simple solution. What we truly get is random P=1/2 bits 0/1 , so what we get is a uniform distribution of numbers eg. for 3 bits from 0 to 7. Doing rand % 5, if a random number takes the value 6 or 7, gets mapped to 1 or 2, effectivelly increasing 1,2 frequency making distribution non-uniform. To avoid that you need something like a state machine which rotates the mapping eg. 6,7 maps to 1,2 then to 3,4 then 5,0 and it goes on. We could also throw away 6,7 whenever they came up. Anyway that's a library implementation problem.

Another approach:  Don't.
Instead:
while (Segments.Count > 3)
{
    Segment A = Segments[Segments.Count - 2];
    Segment B = Segments[Segments.Count - 1];
    Segment C = new Segment(B.End, A.Start);
    Triangle T = new Triangle(A, B, C);
    Segments[Segments.Count - 2] = C;
    Segments.RemoveAt(Segments.Count - 1);
    if (B is inside the new shape Segments)
        Area -= T.Area;
    else
        Area += T.Area;
}
Area += new Triangle(Segments[0], Segments[1], Segments[2]).Area;

Basically, lop off a triangle.  The area of a triangle is simple and in doing so we reduced the segment count of the remainder by one.  Repeat until what's left is a triangle.

Gauss' Shoelace formula is a shorthand for this that halves or thirds the number of calculations. Work it out.


text:
Is Opengl 2.x still usable?
i've used opengl core profile for a while now and i was wondering if it was possible to create a "decent" application (like a game/game engine) with good graphics. I have a machine which can run only OpenGl 2.1(raspberry pi3), i already know the advantages of core profile, but is Opengl 2.x still usable for today's standards?

OpenGL 2 only has relatively few aspects, that would stop this from happening. The fact that you use a raspberry pi is a bigger bottleneck.

So, because of this i am limited by the raspberry pi instead of Opengl 2.x? Are there some examples in which Legacy opengl is used?

Raspberry pi is not full OpenGL 2, it's ES2 and is therefore missing functionality.

OpenGL  ES 2.0 is actually still very common in the market as can be seen by computingfreak's answer in https://stackoverflow.com/questions/5110431/opengl-es-versions-on-different-devices.

Duplicate of https://gamedev.stackexchange.com/questions/1606/is-learning-opengl-2-1-useless-today

First of all, you are very confused.
There is OpenGL ES 2.0, and there is desktop OpenGL 2.0 and 2.1. These are very different things, which run on entirely different platforms. ES runs on primarily mobile hardware, while desktop GL runs primarily on desktop hardware.
The core/compatibility distinction only exists for desktop GL, not OpenGL ES.
Raspberry Pi, of any version, does not support desktop OpenGL of any version. It only supports OpenGL ES 2.0.
As for what you can do with ES 2.0, a lot. You'll find Raspberry Pi's GPU to be limiting from a performance point of view, but you will have access to basic shader functionality. You can do a lot with that.

So if i write a program using opengl es 2 i can run(with of course all the required tools to create an apk) it on android, or any type of machine equipped with an arm processor. Right?

@GabrieleVierti - wrong; the graphics API is only a part of what you need for portability; you also need to port sound, networking, windowing, and anything else platform-specific.


text:
Should I worry about Youtube Let's Plays when I'm creating a story-heavy game?
A few years ago, I watched a full playthrough of the first three Phoenix Wright games on Youtube. I enjoyed the story and characters a lot, hence why I pretty much binge-watched what is a series of very story-heavy games. I know it sounds stupid, but that's what happened.
As a consequence, I had no reason to buy and play any of those games. In hindsight, I realize I pretty much pirated the games without ever even playing them. It's not like I enjoyed the games because of their epic gameplay, I enjoyed them because of the story, and since I know what's going to happen, I don't have a reason to play them myself.
I still bought them in the end out of principle (even if it's Capcom...), but how many people are seriously going to do that? I doubt very many.
Now, I'm in the middle of creating my own story-heavy game, and I'm unsure because of how popular gaming channels have become on Youtube. I fear some big youtuber will play my game, a big portion of my potential playerbase will see the story and not be bothered to buy the game themselves. I mean, why should they if they've seen the story? Sure, I get some free publicity/marketing for my game, but what good is that if nobody's going to buy the game?
Is my concern valid? Or am I too pessimistic about people?

I feel I should note that some games I am curious about so watch a lets play and then think "This looks like a cool game" and deliberately stop watching so I can play it myself without spoilers. So sometimes viewing a lets play might stop a sale but equally other times it might create a sale.

For me, Let's Plays have taken the place of demo versions. When I can't make up my mind if I would like to buy a game or not from just looking at screenshots (possibly manipulated), trailers (likely cut to make the game look more interesting than it actually is), media reviews (possibly bought) or user reviews (rarely objective), I watch some Let's Play footage to get an impression how the game actually plays.

You may lose a sale from one person watching a video, but if they didn't like what they saw you lost nothing, if they did they may tell others and encourage them to buy. Additionally your next game will have a much larger audience if your first game was well received so you are building a future market for yourself

@Philipp, same. I find it frustrating that so many game trailers are just pre-rendered cutscenes, and show nothing about what the player can do and what it is actually like to play the game. Even in a more linear, story-focused game, I need to see a player walking around in-game before I'll consider spending money or filling up my hard drive.

Just adding a comment here because so many others have already answered the question, but I've purchased more story driven games by watching Let's Plays than games that didn't have one of my favorite Youtubers playing it.
Stanley Parable, Abzu, Beginner's Guide, etc.  I've purchased all of these games after watching partial or full Let's Plays and have played through them myself and enjoyed them all immensely.

You mean like that crappy borderlands story game? Protip: don't make a game like that unless your IP is awesome.  People either play because your IP is cool or  the game is actually fun to play,  or if you get really lucky, both.

If you think about let's plays, you might want to think about age rating. there are countries where you need a broadcast license to do let's plays, which includes adherence to age ratings

Something you should maybe be considering is why you want to make this game. Regardless of what that reason is, ask yourself if this is a deal-breaker for you. If you're not passionate about getting this game made, honestly, I'm pessimistic about your success, especially if reduced sales due to Let's Players is causing you concern.

Repeat after me: watching game content is not stupid. Watching game content is not stupid.  Twitch streamed almost 5 billion hours of gaming content in 2016. It's not stupid.

Maybe this is a controversial opinion so I'll make it a comment and not an answer: If your game only stands as a story, then it's likely better off being some other kind of narrative experience (i.e. book, movie, comic, anime, etc). If you really want your work to be a game, then there should be some compelling interactivity involved in it. Even if it's just (meaningful) branched story paths, or if it's a full game with interesting mechanics, a game should justify itself being a game -- otherwise it might actually be meant to be something else.

Saying that watching game content is stupid is like saying watching football/soccer is stupid. Don't fret we all do i (that shouldn't be justification for anything, but I hope you feel better).

If i liked your game, I'd buy it just because I liked watching it. Also if it's story driven then there's definitely something the let's player might have missed

It may be worth considering the potential consequences of attempting to stop people from making videos about your game.  As a consumer, my knee-jerk reaction to companies like that is 'they're trying to hide how awful their game is, no buy'.  I doubt I'm alone in this.

I have personally bought the following games (among others) I otherwise may not have because of watching other people play it or discuss it: Minecraft, Assassin's Creed: Syndicate, Prey, Civilization V, WoW Legion expansion, Terraria, Bastion, Firewatch,....  And I can probably find many more games in my library that I wouldn't have bought without watching my favorite youtubers/twitchers play them. And there are ALSO a ton of games I have watched them play that made me go "hmm, I was going to buy that, but I reconsidered".

Your concern is about what people in the game industry call "a nice problem to have".

You do have the legal right to issue copyright takedowns on LPers. But that is not advisable for the reasons other people have mentioned.

That Dragon, Cancer is a short, story-heavy game that had trouble reaching profitability because of Let's Plays.  So yes, this is a valid concern depending on how short and linear your game is.

Here's a random tip: if you're worried about spoilers in thumbnails, provide a (easily visible) asset pack for people to make thumbnails out of that doesn't contain spoilers. Lazy and courteous people will then not be putting obvious spoilers in thumbnails and it'll be easier for the people who care to avoid them. You won't be able to stop those that will make their own spoilerific thumbnails. Just make sure you provide room for individual to brand their content or nobody will want to use cookie cutter premade thumbnails.

Yes, you should care about Let's Players. In fact, you should make your game as appealing to them as possible. Reach out to them and encourage them to play your game.
Let's Players have become one of the most important marketing channels for independent game developers. They are a great way to expose your game to a large and interested audience and most of the time they don't even want any money for it. And exposure is everything in a market as crowded as today's game market. Only those people who know your game exists will consider buying it. I am sure some games like Surgeon Simulator or Octodad would have never been as successful if they weren't played into the ground on Youtube and Twitch.
Regarding your fear that "a big portion of your potential playerbase will see the story and not be bothered to buy the game": Have you calculated how large your "potential playerbase" actually is? There are hundreds of millions of people in the world who regularly buy and play video games. Your "potential playerbase" is practically endless, even if your game only targets a niche demographic. But just as countless as your customer pool is your competition. That's why exposure is so crucial for games.
However, if you are afraid that watching your game is just as good as playing your game, make sure it is not. Add multiple major branches to your story and lots of minor decisions which affect later events in the game. You want the audience to constantly wonder what would have happened if the player had done something different. And do not neglect your actual gameplay. The unique strength of games as a medium is that they are interactive. If you just want to tell your story and don't want any audience interaction to interfere with it, you can just as well write a novel.

"If you don't want to make any use of audience interaction, you can just as well write a book." I suggest you emphasize this sentence.

There is a certain recent game that has some extra dialog for Streamers. Having one of the "villains" of the game suddenly stop talking to say "Oh, you're recording?" and then proceed to say hi to your audience is extremely creepy and one of the must fun aspects of it.

@T.Sar: What game is that?

@T.Sar I would like to recommend this game to some LPers I know who might enjoy it. What is it? (Wish I could just subscribe to an answer.)

@trlkly That would be Doki-Doki Literature Club. It is a visual novel that was recently covered by a varied group of streamers (Including GTLive!) - it starts off as a very pink, lovey-dovey romance but then takes an abrupt left turn into absolute creepiness and meta-horror halfway through it. It is not a game for the faint of heart, by no means.

There's another consideration: a person who watched your game on YouTube may or may not buy your game, but (if he likes it) he's going to spread the word to his friends. At the expense of one person who watched the game, you've expanded your audience, bringing zero, one or more paying customers.

Essentially while a Let's play might satisfy a few people, the potential for increased sales from exposure puts it something like this: 50% of 500 people (That you could maybe reach without Let's play's) VS 25% of 50.000.
The numbers are pulled out of the thin air, but that's essentially the core "pro-Let's Play" argument that many of them(Youtubers and Streamers) argue for.
And I believe they are correct in this, even in a story heavy game. Even minor interactions in a video game can pull people in, making it much more personal, creating a need to play themselves.

@MartinArrJay You are probably correct. Personally, I've purchased several games after seeing their Let's Play's or game reviews. That includes Fallout 4, Skyrim, Azura's Wrath, Dragon's Dogma, Terraria, Starbound... Even my SO's Switch was purchased after seeing a few of its games' Let's Play's. They are advertisement, and all advertisement is positive in the end.

To this I will say:
I am a LPer on one of my channels, and I try my best not to spoil things, but I find that people will skip a channel if they get spoilers unless they are like my wife. She watches because she enjoys watching the games while others play them. She'll watch me play all day, and never touch the game herself (she does game, don't get me wrong). In this case, you're not losing anything. You're still getting the sale of the game to the person and just exposure to the game by the second person.

@S.TarıkÇetin I totally disagree. Visual Novel are huge (in Japan) and many popular/highly acclaimed ones have linear stories. Muv Luv Alternative and Higurashi come to mind, as both are on Steam.

@Euphoric Visual novels where the player doesn't make any decisions, or at least none which matter (aka Kinetic Novels) do not really fulfill the definition of "game" in my opinion. I am not claiming that it's a medium without merit. Just that it isn't really the same thing as a game. So different rules apply to making and selling them. Streaming a kinetic novel from start to finish is definitely piracy.

@Philipp It doesn't matter if it is game or not. What matters is that people are just as willing to "lets play" them as they are "normal" games. Often without any additional value like commentary.

@Philipp Also. The point is that "just writing a book" is quite rude to say if you want to make a story with audio-visual elements of Visual Novel. Its same as saying "just write a book" to movie screen-writer.

@Euphoric If you look at the edit history of this answer, you might notice that I edited "book" to "novel" shortly after posting it. I did this specifically to also include visual novels and kinetic novels as an alternative medium to games.

I had a similar experience to the one you describe with some other game I will not mention, and ended up thinking about it in similar terms as you do.
As Bálint says, it is a double edged sword. Yet that does not mean you cannot get ahead.
What happens when they play the game for an online audience, then that audience gets to know the game. If this were people who would not have known about the game otherwise, they are people who would not have bought the game anyway. Thus, you should not think about this as a loss, but as a missed opportunity.
To exploit that opportunity, you need to sell replay value during the gameplay. After all, most "let's players" (for lack of a better name) will rarely replay a game (most of them have to move on to something else to keep their audience interested), thus having multiple endings or stuff locked behind a complete play through will make it harder for them to present the entirety of the game.
Now, replay value is usually achieved with some variation of choice and consequence, yet that could be harder in a story heavy game as those tend to be very linear. In that case, I would suggest catering to theories. How? You avoid heavy exposition in the game. Let the explanations, backstory, setting, lore, mythology and the rest of the world building to those who want to look for it, and make it as deep as it need be.
Do that correctly and “Let's players” will complete the game and only scratch the surface of what the game has to offer. If people watching them find mysteries in the game, if you inspire curiosity, and if people would like to take the control of the game and go explore more by themselves, then most of the work to sell the game has been done.
In abstract, you want to provide joy of discovery, and if you put a lot to discover, “let’s players” will not discover it all.

I fear some big youtuber will play my game, a big portion of my potential playerbase will see the story and not be bothered to buy the game themselves. I mean, why should they if they've seen the story?

Well, it is not that they "should". Yet, they can be interested in playing the game by themselves if:

They have not seen the whole story because that is not necessary to complete the game. Perhaps you can replay the game with a different character and get a different point of view.
The story is not the only interesting thing of the game. There is a lot of world building beside the story. Then there are the game mechanics that could (and arguably should) be fun and interesting by themselves.

You might be interested in Shandification. The act of telling a story is also the act of picking what is relevant and what is not... there are multiple way to tell the same story by merely changing the point of view. If you can accommodate that in the game and let the player choose on what to focus on instead of dictating it, then you have the potential to make every play through different.
You may even make that literally. For example, the game "Revolution 1979" lets you take the role of a reporter during the eponymous 1979 Iranian Revolution. Although this means that the player is not the protagonist of the history, it allows the player to explore different parts of the history as it unfolds. This allows circumventing the problem of placing the player in command having player action result in something different that the actual history (by being a glorified spectator, you are not in position to change historical events).
See also How a Japanese Indie Studio Kicks Bethesda's Butt at World-Building
Consider also that the experience of playing the game is not the same as watching it. Of course, this is more relevant for an action games (platforming, first person shooting, etc.) - You need to know what you are making, is it a graphic novel or a video game? Consider games like Chrono Trigger, Fallout or your pick of the Final Fantasy series... they do a great job in storytelling and world building, yet they have game mechanics that are (most of them) fun to play regardless of the story.
On the other hand, if you are making something like a detective game, I suggest to find ways to mix things up, so that it does not play the same every time. Crime mystery really suffer in replay value once you know who the criminal is.

Should I look for other ways to monetize my game, just to be sure?

Yes and no.
Not all games fit all monetization schemes. Some games work best in a pay upfront model. In addition, monetization is better when you considered an integral part of the game design (because it can make or break the game).
On the other hand, thinking of ways to monetize the game (even if you end up not doing it) would be a good exercise to find aspect of the design that you could change. For example, if there is a part of the game that could be different thanks to DLS or micro-transaction, that part of the game that could be different, period. If you can make it so that it plays different every time, you have added replay value to the game.

This is very insightful. I learned about some very plot-heavy games such as Sorcery! from Twitch, yet I felt compelled to buy and play them myself due to the copious amount of choices those games provided, despite their generally very linear structure. The more interactivity your game would have, the more likely Youtube exposure would be beneficial to its sales.

Youtube let's plays are double edged swords. On one hand there's the probability, that you'll lose potential players, but there's also the probability, that you'll gain new ones, especially if you're an indie dev.
Most popular indie games become popular in the first place because of them. You can probably name a few from the top of your head; Stardew Valley, Shower with your dad, Flappy Bird, etc.
There were cases of video game companies being afraid of let's players spoiling the majority of story based games. The most recent I know of was Atlus not allowing youtubers to upload let's plays of Persona 5 after a certain point in the game.

And there was a lot of backlash with Atlus's policy on Persona 5. People were intentionally spoiling the story on the Persona 5 Twitter account, and someone even wrote a Persona 5 spoiler bot that posted spoilers for any tweet tagged #Persona5. So there is a potential PR issue, and bad PR for a small dev can be fatal.

Streisand strikes again.

Well, AFAIK, Atlus has been doing this since Catherine. I don't have any idea whether it backlashed at that time though (in the end, I bought and played until the end).


text:
How to achieve single animation for different charcters?
I've been playing a game called Marvel Contesnt of Champions for android. In that game two opponent fights with each other in most 2D view but the game is developed in 3D. Each character has their own special move which dynamically interacts with opponent. So how does they achieve single animation for different characters?
By single animation I mean, for example, I'm playing with X character and he uses his special move on Y character and in that animation X character grabs character Y's neck and smashes him on the ground. Now, I'm fighting Z character with X character and in the special move he smashes Z character same way he smashed Y character. Is it like a common skeletal movements that are just changing their clothes(textures) ?
I'm pretty sure it's not pre-animated thing cause there are like more than 50 characters. I'm currently working in Blender and getting my character design right but this question was bugging me for a while and I thought there could be no better place other than here to clarify my confusion.

When you want a character skeleton to interact with objects in the environment (which might or might not also be a character skeleton), then you usually use a technique called inverse kinematics, often abbreviated as IK (the link leads to the documentation of the Unreal engine, but other 3d engines usually can do this too).
When you play an animation, like for example "grabbing another character's throat", you pass the position of the target object to the animation system. It will then modify the animation of the arm- and shoulder bones so that the hand-bone ends up where you want it to be.
If you have two or more characters which have different body proportions but the same bone hierarchy, then many engines allow you to easily reuse animation sequences between them. That's called animation retargeting.
Having animations where two characters interact with each other is complicated. There are several options:

Fuse the two character skeletons into one for this animation. This gives you the most control over the animation, but might lead to problems when the two characters have different proportions. It might look as if individual bodyparts suddenly grow or shrink during the animation.
Animate both skeletons separately. So one has a "smash other person into the ground" animation and the other a "get smashed into the ground" animation with the attackers hand as one IK target point and the floor as another.
For this specific case of "getting smashed into the ground", you can also just deactivate the animation of the victim's model and use ragdoll physics with the throat-bone being the anchor point of the character model. It will look as if the victim gets thrown to the ground like a wet sack. This might or might not be what you are going for.

But doesn't that still requires me to set animation for other different skeletons too? Or am I understanding wrong? Like, I set a dance animation of X and Y now I changed partner with Z so X and Z will require another defined animation?

Oh the term animation retargeting will surely spread some light. I'll look into it and get back.

Hello, @Philipp 'Animation Re-targeting' was the thing I was looking for. More reading about it solved my confusion. I can't accept comment as answer. So please post the comment again as answer.

@AmanParmar Done.