texts: What is the best way to code the XNA gameserver for an FPS game?

texts:
I'm writing an FPS XNA game. It is going to be multiplayer, so I came up with the following:

I'm making two different assemblies — one for the game logic, and one for drawing it and the game irrelevant stuff (like rocket trails).
The type of the connection is client-server (not peer-to-peer), so every client connects to the server, and then the game begins.
I have decided to use the XNA.Framework.Game class, for the clients to run their game in window (or fullscreen), and the GameComponent/DrawableGameComponent classes, to store the game objects, update, and draw them on each frame.

What should I do on the server side? I got few options:

Create my own Game class on the server, which will process all the game logic, without graphics. I am not using the standard Game class because, when I call Game.Run(), the white window appears and I cant figure out how to get rid of it.
Somehow, use the original XNA Game class, which already has the GameComponent collection and Update event (60 times per second, just what I need).

I have additional questions:

First, what socket mode should I use? TCP or UDP? How do I actually let the client know the order in which packets are meant to be processed?

Second, if I am going to use the exact GameComponent class for the game objects, which are stored and processed on the server, how do I get them to  draw on the client side? Should I inherit them, while they are combined in an assembly), or something else?


texts:
In your game assets do you make room for explicit sanity checks, or do you have some generally expected bounds which you assert?

I've been thinking about how we compress data and thought that it's much better to have the former, and less of the latter. If your data can exceed your normal valid ranges, but if it does it's an error, then surely that implies you're not compressing the data well enough?

What do you do to find out if your data is compressed as far as it can be, and what do you use to ensure your data isn't corrupted and ensure it's an official release?

EDIT

I'm not interested in sanity checking the file size, but instead, how you manage your sanity checks and whether you arrange the excess size caused by the opportunity to do sanity checks by using explicit extra data, or through allowing the data enough file space (data member size) to be out of valid range and thus able to be checked merely by looking at the asset in memory after loading.

EDIT

QUOTE:
"runtime performance is valued very highly while maximal compression is merely a nice thing to have"

yes, but we're still having issues with our media being slower than decompression algorithms, especially with situations where programmers and data desginers have not considered the footprint of their data layouts and are unnecessarily creating assets that have redundant storage capacity.

I must assume that there are very few people who consider the importance of bandwidth outside of those working on platforms that are strictly bound by their data throughput rate or storage capacity.


texts:
I have this quest manager script where I store all my quests for easy duplication.

I'm adding a feature that gives the player the option to see his/her current to-do quest.

The first thing I tried was just showing it in my dialogue box(which closes immediately because it's supposed to be for dialogues only).

Now I made a quest log UI so he/she can see his/her current to-do list with a claim button for the reward.

All I need to do now is to change the text I have in the quest log UI (the Quest Title and the Description) the same way I was doing with the dialogue for each quests, but I can't seem to figure out how.

public QuestObject[] quests;
public bool[] questCompleted;

public DialogueManager theDM;
public PanelManager thePM;

public string itemCollected;

// Use this for initialization
void Start () {
    questCompleted = new bool[quests.Length];
}

// Update is called once per frame
void Update () {

}

public void ShowQuestText(string questText)
{
    theDM.dialogLines = new string[1];
    theDM.dialogLines[0] = questText;

    theDM.currentLine = 0;
    theDM.ShowDialogue();
}
public void ShowQuestList()
{
    thePM.ShowDialogue();
}

public class QuestObject : MonoBehaviour {

public int questNumber;

public QuestManager theQM;
public DialogueManager donMariano;

public string startText;
public string endText;

public string questTitle;
public string questDescription;
public int rewardGold;
public int rewardChilli;
public int rewardEggplant;
public int rewardPotato;

public bool isItemQuest;
public string targetItem;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if(isItemQuest)
    {
        if(theQM.itemCollected == targetItem)
        {
            theQM.itemCollected = null;

            EndQuest();
        }
    }
}
public void StartQuest()
{
    theQM.ShowQuestText(startText);

}
public void EndQuest()
{
    theQM.ShowQuestText(endText);
    theQM.questCompleted[questNumber] = true;
    gameObject.SetActive(false);
}

}

public class DialogueManager : MonoBehaviour {

    public GameObject dBox;
    public Text dText;

    public bool dialogActive;
    public string[] dialogLines;
    public int currentLine;

    public Image[] dialogImage;

    private PlayerControl thePlayer;
    // Use this for initialization
    void Start () {
        thePlayer = FindObjectOfType<PlayerControl>();
    }
    // Update is called once per frame
    void Update ()
    {
        if(dialogActive && Input.GetKeyDown(KeyCode.Space))
        {
            currentLine++;
        }
        if(currentLine >= dialogLines.Length)
        {
            dBox.SetActive(false);
            dialogActive = false;

            currentLine = 0;
            thePlayer.canMove = true;
        }
        dText.text = dialogLines[currentLine];
    }
    public void ShowBox(string dialogue)
    {
        dialogActive = true;
        dBox.SetActive(true);
        dText.text = dialogue;
    }
    public void ShowDialogue()
    {
        dialogActive = true;
        dBox.SetActive(true);
        thePlayer.canMove = false;
    }
}


texts: running GL ES 2.0 code under Linux ( no Android no iOS )

texts:
I need to code OpenGL ES 2.0 bits and i would like to do this and run the programs on my desktop for practical reasons.

Now, i already have tried the official GLES SDK from ATI for my videocard but it not even runs the examples that comes with the SDK itself, i'm not looking for performance here, even a software based rendering pipeline could be enough, i just need full support for GLES 2.0 and GLSL to code and run GL stuff.

There is a reliable solution for this under Ubuntu Linux ?


texts: How can I compile SM 3.0 effects in D3D11 in SlimDX?

texts:
var bytecode = ShaderBytecode.CompileFromFile("shaders\\testShader.fx", "fx_5_0", ShaderFlags.None, SlimDX.D3DCompiler.EffectFlags.None, null, null, out str);
var effect = new SlimDX.Direct3D11.Effect(gpu.Device, bytecode);

This works fine but if I try to use another shader model like 4.0 or 3.0 it throws an error on the new effect creation:

E_FAIL: An undetermined error occurred (-2147467259)

How do I compile older shaders?  And I've read about device context but I can't find any information on how to use them to maintain DX9 compatibility.


texts: Examples of transforming camera in its local coordinates vs world coordinates OpenGL

texts:
I am trying to learn OpenGL and am doing some beginners learning exercises. One of the exercises is to translate and then to rotate the camera along its own local coordinates and not the world coordinate system.

I am at a loss at how to do one vs the other. I'm aware how to perform translations and rotations using glTranslatef() and glRotatef() functions. Through research I'm also aware of using the 4x4 transformation matrix to multiply our vector/s with to create the desired transformations, although I've not yet messed around with it personally so I'm not too familiar with the transformation matrix.

This being said, I still have questions regarding the local vs world coordinates. I understand that we can put into effect translations and rotations via these functions or the transformation matrix, but I'm concerned with understanding how we do one vs the other. I haven't found any explicit code/examples of transforming a camera (or a model, but I'm more concerned with the camera in this instance) with respect to the world coordinates, and likewise for transforming it with respect to its local coordinates. I feel like at this point I need something rather explicit, because I've felt confused for several days now.

Furthermore, there may be some conceptual things I am confused about. This is to my understanding: If we strictly move objects and the camera (which to my understanding functions like any other object in the world) by the local coordinate system, does that mean that all the local coordinate systems share the same position of their origin with each other and the origin of the world coordinate system? Then, on the other hand, if we strictly move objects/camera with respect to the world coordinate system, then all objects will always be on their own local coordinate system's origin, right? And assuming no object is positioned on the same spot, then no local coordinate systems origin will be positioned on the same spot, right?


texts: How can I make that on escape press it will load back the main menu?

texts:
This script is attached to another scene that is not the main menu scene:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadMainMenuOnclick : MonoBehaviour
{
    private Scene scene;

    // Use this for initialization
    void Start ()
    {
        scene = SceneManager.GetActiveScene();
    }

    // Update is called once per frame
    void Update ()
    {
        if (scene.name != "Menu")
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                SceneManager.LoadSceneAsync(0);
            }
            //To check that if in gameplay mode
            //f in The Space Station scene or any other scene
            //that is not the main menu scene only then to be able
            //to click on escape key to load the main menu
            //and to check why the exit button and sound not working
            //when clicking pressing the escape key.

            // And here to also pause the game !!!!!
            // to check how to pause the game here when
            // clicking the escape key.
        }
    }
}

What I want is when I click the escape key to load the main menu scene that index 0 and then to pause the game. I don't want to unload or remove the current active scene when pressing escape I wan to keep both scene loaded when loading the main menu.

Not sure if to use LoadSceneAsync or just LoadScene.

When I start the game both scenes are loaded and the active scene is not the main menu but I see and use the main menu scene.

Then I click on a start game button and it's unloading the main menu scene:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadScenes : MonoBehaviour
{
    // Use this for initialization
    void Start ()
    {
        SceneManager.LoadScene(1, LoadSceneMode.Additive);
        StartCoroutine(WaitForSceneLoad(SceneManager.GetSceneByName("The Space Station")));
    }

    public IEnumerator WaitForSceneLoad(Scene scene)
    {
        while (!scene.isLoaded)
        {
            yield return null;
        }
        SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));
    }
}

When the game is running there are two loaded scenes: "Main Menu" and "The Space Station" The active scene is the "The Space Station" but the scene that load first is the main menu.

When I click the Start Game button it's unloading the Main Menu scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadSceneOnClick : MonoBehaviour
{
    public void ActivatePlayer()
    {
        GameControl.player.SetActive(true);
        SceneManager.UnloadSceneAsync(0);
    }
}

Now when I press escape I want to get back to the main menu scene to load it again and to pause the "The Space Station" scene.

I also want to save the game progress so far when pressing on escape.
So it will pause the game but also will save the progress so far to a file on the hard disk.


texts: How do I make the player gun stop firing when sprinting

texts:
I am trying to get the players gun to fire when the player is walking and the stop firing when the player starts to sprint. The gun will work just fine and ire when the player is walking, but it will continue to fire when they start running and they can also start firing when they are running. I have been trying or most o the day and have not been able to figure out how to fix this.

The top script is obviously the script or the gun firing and whatnot and the bottom script is the controller or movement as well as the animation for the gun.

EDIT: Still no luck.

public class Shooting : MonoBehaviour
{
    private float NextTimeToFire = 0f;
    public bool AllowedToShoot = true;

[Space(10)]
    [Header("Floats")]
    public float Damage = 10.0f;
    public float Range = 100.0f;
    public float ImpactForce = 60f;
    public float FireRate = 15f;

    [Space(10)]
    [Header("Others")]
    [Space(5)]
    public Camera FPSCamera;
    public ParticleSystem MuzzleFlash;
    public GameObject impactEffect;

void Start()
    {
    }

    void Update()
    {
            if (AllowedToShoot == false) return;
            {
            if (Input.GetButton("Fire1") && Time.time >= NextTimeToFire)
                {
                    NextTimeToFire = Time.time + 1f / FireRate;
                    Shoot();
                   }
            }
    }

    void Shoot()
    {
        MuzzleFlash.Play();

            RaycastHit hit;
            if (Physics.Raycast(FPSCamera.transform.position, FPSCamera.transform.forward, out hit, Range))
        {
            Debug.Log(hit.transform.name);
            Objects enemy = hit.transform.GetComponent<Objects>();
            if (enemy != null)
            {
                enemy.TakeDamage(Damage);
            }

            if (hit.rigidbody != null)
            {
                    hit.rigidbody.AddForce(-hit.normal * ImpactForce);
            }
            GameObject ImpactGo = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
            Destroy(ImpactGo, 2f);
        }
    }
}

///

public class WeaponMovement : MonoBehaviour
{
    public GameObject CameraAnimations;
    Animator anim;

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

    void Update()
    {
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                anim.SetBool("Sprint", true);
            }
        }

        if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.UpArrow))
        {
            anim.SetBool("Sprint", false);
        }

        if (Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.RightShift))
        {
            anim.SetBool("Sprint", false);
        }
    }
}


texts:
My game completely uses baked lighting in URP and because of URP's forward renderer, point and spot lights can't cast realtime shadows on moving characters if I set their types to mixed lighting, and my game mostly takes place indoors, so directional lights wouldn't make sense.
So now, I thought I'd use the blob shadow projector from the standard assets pack and it didn't work then I found out that it does not support URP.
Does anyone know how I can recreate the blob shadow projector for URP? Or is there another way to create fake shadows for non-static characters?


texts: Handling collision for sprites with different frame sizes

texts: I am creating a platform game, and the main character has three images for its left and right animation. The problem is that when it is walking and the player run into a block, if at that moment it switches to a stepping image which is bigger than the other imagesit gets stuck inside the block.  A temporary fix to this issue was to make all the images the same size and just fill the smaller ones with white-space, however that doesn't work properly either because then the collision box is bigger than the player.  Any suggestions?  I also tried stretching all the images to the same size but that looked ugly.


texts: How can I display an image larger than the screen and allow the user to scroll to see more?

texts:
I am new to development and trying to understand my options.  I have found no info or threads on this idea so I was hoping some of you folks could weigh in.

When developing for Android, I know that different images optimized for different screen densities and sizes are typically used.  I am wondering if anyone just flicks in the resizing and develops so that the smallest device (i.e. phone) shows enough of say a game world to make it relevant for the user and larger screens (i.e. tablet) just show more of that world but at the same scale.

I guess you would have to have a couple versions for different densities or graphics could appear too small, but it could really cut down on the number of asset files the user would have to download.  Though the whole background/world image would be one big file.  I assume when downloading an app graphics files for all screen sizes and resolutions are downloaded and then the app detects the screen size and chooses from among them for display.


texts: In MMO game, how to handle user characters, who are offline?

texts:
In my medieval MMO game, players have their own character, that represents themselves inside game. Like a King. Players could have cities and armies, but King acts as main driving force.

Then it comes to player, going offline/vacation/disconnect. How to deal with "offline King", to keep some sort of reality in game, without ruining everything for player.
I have never liked unrealistic stuff in games, like appearing/dissapearing from thin air, like in WoW or other MMO RPG's, when it comes to connect/disconnect, like in Matrix movie, when you are disconnected, your "avatar" inside the system just vaninshes.

Ok, if player char stays where it was left, other players who are online could kick his ass like offline player char was frozen? I see only one solution - give player char, while offline, some sort of AI, that controls char. Is there any other solutions? May be, some sort of legend/story, could make users only as inner-voice, leaving King just passively controlled by user, or other stuff... Please, help!

I hope you understand my question.


texts: Making a parent system with euler angles (gimbal lock problem)

texts:
I have a system where objects can be connected to each other - as the parent rotates the child objects will rotate too and child objects themself can rotate too. The system is already working, however, I am doing it with rotation matrices.
I want to dynamically simulate angular physics and for that, I would need the angular velocity for which I thought the direct and easiest way would be to get the difference of the euler angles.
I am still a beginner with those rotation maths like matrices, quaternions etc.
The problem is that the rotation of the children would be local and currently I am just adding the euler angle values (which works fine if I only rotate around one axis). So when I rotate a child on the x axis by 90 degrees and then rotate the parent on the y or z axis the system breaks (y and z should be swapped in this scenario with 90 degrees x rotation)
As far as I have understood it the problem could be explained with "gimbal lock".
Is there a way to calculate the local euler angles? Or is there in general a better way to achieve what I am trying to do here? I have heard that quaternions also don't save 360+ degrees, so that would be also a problem for angular velocity.


texts:
Ambiguity:
What exactly is the difference between Tiling the material and Offset of material?

Need to do:

I need the material to be repeated n times on the object where I need to set the value of n via script.How do I do it?

It seems to happen through Tiling(tried via inspector) but again what is difference between mainTextureOffset and setTextureOffset?

Tried:

Following is the line of code that I tried to repeat the texture n number of times on an object(repeat across the width of object), but it does nothing significant that I can see.


texts:
I've developed several games for the android platform and now planning to create my first multiplayer game. What I have in mind is basically just a 2-player game witch you can play with 2 phones over local area connection/WiFi.

Both phones need to be able to pass 3 integer values to the other phone in real time. So far I have considered using Socket's, but before I dig into it too deep I wanted to ask if there might be a better approach?

Thanks!


texts: Sweep and prune vs quad tree when all objects are dynamic (moving)

texts:
As I understand it there are 3 popular strategies for spatial partitioning: sweep and prune, quad/oct tree and uniform grid. Uniform grid is problematic for me because I have not set an upper limit on how big each entity can become so every time an entity move I may need to update multiple grids.

So right now I am exploring sweep and prune vs trees on which is better for my use case. I know for sure that a majority of my objects contained in the structure will be moving every frame. I need to support 2 tests: 1) whether any objects overlap/collide with each other and 2) whether any object will overlap/collide with a ray that can traverse through the entire playing region.

I know for question like these the answer is usually impossible to know beforehand without testing etc. But certainly this is a very common problem and many of you have experience with.  If so, can you share the strength/weakness of each method with respect to my use case and which method is more likely to produce better results? And for the record I am trying to animate 1k+ dynamic entities in 3D space so brute forcing is unlikely to be enough. I also have another structure for static objects so all contained entities are dynamic.


texts:
Why does AudioSource not initializes itself?

Here is my code:

    using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraConfig : MonoBehaviour
{
    public GameObject objToFollow;

    public bool followRabbit;

    // Use this for initialization
    void Start()
    {
        followRabbit = true;
        LevelController.current.cameraWhichLooksForRabbit = this;

        setMusicSource();
        setSoundSources();
    }

    public AudioClip music, rabbitWalksSound, rabbitDiesSound, rabbitFallsSound, enemyAttacksSound;
    private AudioSource musicSrc, rabbitWalksSrc, rabbitDiesSrc, rabbitFallsSrc, enemyAttacksSrc;

    private void setMusicSource()
    {setClipForSrc(musicSrc, music, true);}

    private void setSoundSources()
    {
        setClipForSrc(rabbitWalksSrc, rabbitWalksSound, false);
        setClipForSrc(rabbitDiesSrc, rabbitDiesSound, false);
        setClipForSrc(rabbitFallsSrc, rabbitFallsSound, false);
        setClipForSrc(enemyAttacksSrc, enemyAttacksSound, false);
    }

    private void setClipForSrc(AudioSource src, AudioClip clip, bool loop)
    {
        src = gameObject.AddComponent<AudioSource>();
        src.clip = clip;
        src.loop = loop;
    }

    void Update()
    {
        checkMusicAndStopOrStartIfNecessary();

        if (!followRabbit)
        { return; }

        Transform rabit_transform = objToFollow.transform;
        Transform camera_transform = this.transform;

        Vector3 rabit_position = rabit_transform.position;
        Vector3 camera_position = camera_transform.position;

        camera_position.x = rabit_position.x;
        camera_position.y = rabit_position.y;

        camera_transform.position = camera_position;
    }

    public void playSoundRabbitWalks()
    {
        if (!rabbitWalksSrc.isPlaying)
        { rabbitWalksSrc.Play(); }
    }

    public void playSoundRabbitDies()
    { rabbitDiesSrc.Play(); }

    public void playSoundRabbitFalls()
    { rabbitFallsSrc.Play(); }

    public void playSoundEnemyAttacks()
    { enemyAttacksSrc.Play(); }

    public void stopSoundRabbitWalks()
    {
        if (rabbitWalksSrc.isPlaying)
        { rabbitWalksSrc.Stop(); }
    }

    public void stopSoundRabbitDies()
    { rabbitDiesSrc.Stop(); }

    public void stopSoundRabbitFalls()
    {rabbitFallsSrc.Stop();}

    public void stopSoundEnemyAttacks()
    {
        enemyAttacksSrc.Stop();
    }

    private void checkMusicAndStopOrStartIfNecessary()
    {
        if (SoundManager.Instance.isMusicOn() && !musicSrc.isPlaying)
        { musicSrc.Play(); }
        else if(!SoundManager.Instance.isMusicOn() && musicSrc.isPlaying)
        { musicSrc.Stop(); }
    }
}

Here are screenshot of the exceptions in console and inspector view:


texts: Disable audio listener warnings? "There are no audio listeners...", "There are 2 audio listeners..."

texts:
The scene I'm working in constantly spams the message There are no audio listeners in the scene. Please ensure there is always one audio listener in the scene. If I add a dummy camera with an Audio Listener, I then get There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene.

I know this happens because our camera is created programmatically, with an audio listener.  I also realize this will not affect the non-development build in any way.

Is it possible to disable these warnings completely?


texts: What techniques are useful for modelling Character Actions via OOP?

texts:
I'm trying to rewrite a legacy php Browser-Based-Game so that it uses object oriented programming.  I find it relatively easy to model concrete nouns, like: new Npc(), new Character(), new Account(), new Clan().

I'm finding it more difficult to model a character's actions.

For example:

usable skills.
a test for whether two characters are multiplayers
attacking another character
test for whether a character is allowed to attack another character
etc.

Have you done something like this, and if so, what overall approach did you use to model the in-between-the-nouns behavior?


texts: Should I be returning weak/shared_ptrs or unique_ptr's to my resources?

texts:
A friend of mine told me instead of normal pointers, I should use unique_ptr, i asked him why unique_ptr's if some resources are going to be shares, like multiple grass tiles, or enemies. I currently use this:

    std::map<ResourceTextures /* this is just a int */,
    std::unique_ptr<sf::Texture>> _textures;

Shouldn't I be using shared_ptr instead? That way I can keep the reference count, and unload resources as they have 0 references?

Also one more question, currently, I am passing my resource manager in every file, is there a way to make it so that all my functions dont require this:

Level(ResourceManager& resMan);
Tiles(ResourceManager& resMan);

A level is an array or tiles, should i just make it inherit tiles, so that i don't have to pass around my resourceManager everywhere?

Thanks for the help guys, after 2 years of doing nothing programming, I'm trying to make a simple game!


texts: How to calculate object speed so it accelerates exponentially?

texts:
Think a rocket or a missile. Completely don't know how to make it start slow and then get progressively faster in an non-linear fashion, given max speed and base acceleration. Curve like this would look best.

 ^                       .
S|                       .
 |                      .
 |                    ..
 |                ....
 |         .......
 | ........
 +------------------------>
                         T


texts: How to simulate acceleration and then deceleration?

texts:
Currently I am only using deceleration.

Here is how I do it

I need to cover Vector(x,y) unit distance to reach B from A.

I simply do -

rendering loop->

position = A + Vector(x,y).scale(factor);
Vector(x,y) = Vector(x,y) - Vector(x,y).scale(factor);

...factor = 10 for example
So if I have to cover 100 units, I cover 10 then 9 then 8.1 and so on in every frame.

How do I simulate acceleration then deceleration here?


texts:
I have 2 methods, one to rotate my Quad and one to flip it (using scaleM), they are as follows: (Note, all values in these methods have been properly defined).

If I call just one, they work as expected, but if I call both, then only the one that is called last if applied - why is this?  If I combine them into on 'flip and rotate method' - then my quad is both flipped and rotated. (See third code snippet)

Why is this?

Method to rotate

    public void rotate(float x, float y, int angle){

    //Rotate the quad

    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.rotateM(mRotationMatrix, 0, -angle, 0, 0, 0.1f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);

}

Method to 'flip' (horizontally)

    public void flipHorizontal(float x, float y){

    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.scaleM(mRotationMatrix, 0, -1, 1, 0f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);
}

Combined method

    public void flipHorizontal(float x, float y, int angle){

    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.rotateM(mRotationMatrix, 0, angle, 0, 0, 0.1f);
    Matrix.scaleM(mRotationMatrix, 0, -1, 1, 0f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);

}


texts: Rendering multiple textures on a terrain in XNA / C#

texts:
I am working on a terrain in XNA/C#. My intention is to be able to render multiple textures on the ground across the terrain. However, all tutorials like this are only capable of doing it with about 3-4 textures.

My idea is currently that I create a texture map in TGA that has different colors (RGBA) where each color represent a particular texture. The amount of Alpha in the color describes how much alpha the vertex on the position should have. And there would be a base texture.

However, I am a newbie in this area so I really need some getting started guides. So far I've managed to found none. All tutorials and resources are limited in terms of how many textures they support even though all modern games have many.

My game is an RTS, and having played a lot RTS games, I've noticed they all support lots of textures across the terrain. For example, the world editor for Command & Conquer 3 allows you to place any amount of any texture anywhere.


texts: How to scale our multiplayer support, similar to Among Us

texts:
We are a small team with the goal of creating our first multiplayer game, and we want to support multiplayer that can rapidly scale up as Among Us has successfully done.
We don't have a huge budget and we are struggling to find an appropriate way to implement multiplayer, including peer to peer (although it would be exhausting to combat cheating and make a smooth experience). Our game has no more, no less than 50 players in a very tight space.
As an example, we're looking at the indie game Among Us. They went from such a small game with barely any players, to maintaining well over 3 million CCU (concurrent users). How can we achieve similar scalability?


texts:
We are small indie team developing a casual mobile game.
We are trying to implement an effect like the normal-to-ice block transition in Angry Birds 2:

How can we implement an effect like this in Unity?


texts:
I'm planning to get into Unity 2D tools - so in order to start off I decided to create a little breakout clone. However, I'm not sure how to manage levels. When I wrote Breakout using MonoGame, I just had one class Level which read a XML-file for the level itself (kind of a simple tilemap).

Now that Unity has a graphical interface I could probably just create one scene for each level and put all the blocks in there. Is this a normal approach to handle levels in Unity - or would it be more appropriate to have one scene that also loads objects by using something like a XML file?

Thanks!


texts: How to properly differentiate single-clicks and double-click in Unity3D using C#?

texts:
What I am trying to understand and learn here is a very basic thing: what is the most general and most polished way to properly differentiate single-clicks and double-clicks for the 3 main mouse buttons in Unity, using C#?

My emphasis on the word properly is not for nothing. Although I was surprised that this seems to have never been asked in this website before, of course I have searched and found numerous similar questions on Unity's forums and Unity's own question-answer pages. However, as it is often the case with answers posted in these resources, they all seemed to be either plain wrong or at least a bit too amateurish.

Let me explain. Proposed solutions always had either of the two approaches and their corresponding flaws:

every time a click happens, calculate time delta since last click and if it was smaller than a given threshold, a double click would be detected. However, this solution results in that a quick single click is detected before the double-click is detected, which is undesirable in most situations because then it activates both single and double click actions.

Rough example:

float dclick_threshold = 0.25f;
double timerdclick = 0;

if (Input.GetMouseButtonDown(0)
{
   if (Time.time - timerdclick) > dclick_threshold)
   {
       Debug.Log("single click");
       //call the SingleClick() function, not shown
   } else {
       Debug.Log("double click");
       //call the DoubleClick() function, not shown
   }
   timerdclick = Time.time;
}

set a wait-for delay for the single-click to be activated, which means, at every click, only activate single click actions if the time delay since last click is above a given threshold. However, this gives sluggish results, since a waiting before it is possible to notice the waiting before single-clicks are detected. Worse than that, this kind of solution suffers from discrepancies across machines, since it does not take into account how slow or how fast is the user's double-click speed setting at the OS level.

Rough example:

   float one_click = false;
   float dclick_threshold = 0.25f;
   double timerdclick = 0;

   if (one_click && ((Time.time - timerdclick) > dclick_threshold))
   {
       Debug.Log("single click");
       //call the SingleClick() function, not shown
       one_click = false;
   }

   if (Input.GetMouseButtonDown(0))
   {

       if (!one_click)
       {
           dclick = -1;
           timerdclick = Time.time;
           one_click = true;
       }

       else if (one_click && ((Time.time - timerdclick) < dclick_threshold))
       {
           Debug.Log("double click");
           //call the DoubleClick() function, not shown
           one_click = false;
       }

   }

Therefore, my questions becomes the following. Is there a more polished and reliable way of detecting double clicks in Unity using C#, other than these solutions, and one that handles the problems aforementioned?


texts:
My class X is interited from CCLayer.

@interface X : CCLayer

Then in X, I added an instance variable of type CAShapeLayer.

CAShapeLayer *_Circle

I drew the Circle using UIBezierPath. Now if I try to add _circle to self, it gives me error:

[self addChild:_Circle];

[CAShapeLayer tag]: unrecognized selector sent to instance 0x916f7f0 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CAShapeLayer tag]: unrecognized.

I also tried typecasting _Circle to (CCNode*) or (CCSprite*) but nothing helped.

Any suggestions?


texts: Best way to interpolate player movements in a very fast paced Unity game?

texts:
In my Unity online multiplayer game players move very fast and I currently use Lerp to interpolate between their last position and current position:

transform.position = Vector3.Lerp(transform.position, this.correctPlayerPos, Time.deltaTime * smoothingFactor);

smoothingFactor is currently around 35f but I don't like the result. If I lower smoothingFactor, movements will be smoother but players will lag as well. If I increase it to like 40, it will be more precise but laggy.

How can I solve this?


texts:
I am working with Unity and C#, but my Problem is a more general programming problem. I am trying to keep things easy, but still make them global access able and easy to modify.

So I have a Character_Model_Selection class, in which You can scroll from the right to the left with shifting for example to your desired model and then select it . An Id keeps track of which model is infront of the User on select. If He selects it, I compare that Id With an Integer and If it is equal to it, I pass it a string of the actual "hero" name . Before I used a singleton to create an default instance,  modify the Name and then access it in the Main screen, but since I have multiply Players with different spawns singletons doesn't really make sense anymore.

Question: What design Pattern or technique could I use to have a  Base class of a Player hero, which has some default properties, like health and pushforce. With I can create  multiply instances of but make it global access able and modify the default properties on select.


texts: Using Google Play In-App purchases in Amazon store, can it be done?

texts:
I have an app currently in the play store (it's free), and google play IAPs are implemented in the app.

I'm new to the Amazon store, but if it allows me to upload an APK as is, what is to prevent my game from allowing users to make in app purchases via google play using an app they downloaded off Amazon? Would I be absolutely required to set up IAPs for Amazon if I use their store?


texts: Animation playing incorrectly when controlled through player

texts:
I have a 2D simple directional blend tree with 2 inputs, X and Y, for movement.

If i move the red dot in the inspector, the animations blend nicely. Same if i move the 2 input parameters in the animator. But if i press play and move the character with arrows, i can see the 2 parameter inputs  in the animator screen moving same as when i moved them with mouse, but the animation that is playing stays the same and the red dot that represents parameters in the inspector stays in the center (even though the parameters in the animator are moving).

I also tried using just 2 animations and blending between them, but turns out that doesn't work ether, even though animator shows that the correct animation should be playing. (if i press forward animator shows that forward animation is playing, but on scene the animation that is playing is like a blend at parameter value in the middle.

The animations were made in Blender as actions (if that's important).


texts:
I assume as the Bolt is an asset for Unity then I could ask my question about Bolt here.
I couldn't find any tutorial about how to read a file in Bolt?
Can anyone help me?


texts: How can I facilitate communication between "attack" and "movement" components?

texts:
I'm currently programming in Unreal, but this is more of a component oriented design question.

I'm trying to follow a component driven aproach, and I have currently achieved creating a movement component which gets connected to the character object, it can do the following (apart from the usual walk, jump behaviour)

WallSlide/WallClimb (like parkour) on Walls that the character cannot climb.
Ledge Grab when reaching the apex of a wall, the character will start grab the ledge and climb to the end so he can be on top of the ledge.
Hook Movement Implementation: you set a target point and the movement component will make the character travel to that point, triggering an event when it reaches the destination or it's interrupted by something in it's journey

The problem is that I'm right now trying to figure where and how to put the "attack" actions of the character. Say I make an Attack component, how do I deal with the weapon or attack wanting to move the character while the movement component is wanting to do the same thing (think of a shoryuken or a stinger)?

The thing that confuses me is that the movement is the domain of the movement component, and adding the movement logic of the combo breaks the decoupling of the modules, if I have to program the movement component thinking of the attack component.

I know this is an abstract question and i have asked it aroud everywhere, but I just cannot find some good material on how to approach this, every place I check, they use some "patch like" programing where they program directly to the character and don't worry decoupling the behavior.


texts: multiple contacts for SAT collision detection

texts:
I have implemented SAT algorithm for obb-obb intersection and I am able to generate a contact for this collision type. My problem is that SAT only generate ONE contact and in many situation I need more than one contact. For example, If I have a big cube and above it I have a small cube I need two contact (two contacts in 2D and 4 contacts in 3D) one for each bottom vertex of small cube.

My question is how can I generate more than one contacts with SAT?

Thanks.


texts: How do I let people make Steam Workshop mods for my game?

texts:
I want to know how to make a game compatible with Steam Workshop. Basically, I want to be able to let players make mods for my game. Using Google, I keep finding tutorials for how to make mods for popular games, but not how to make one generically.

I am using Godot engine which has builtin support to make it easy to let people mod your game. My game is network enabled and uses ENet with RPC calls (I don't think the networking matters, but in case it does, I am mentioning it).

How do I let people upload mods they made for my game so others can just subscribe to it and have it loaded in the game?

I did check out Valve's Create a Mod page, but it only talks about how to make one for source engine games. Looking at Valve's Mods on Steam page, they mention to ask the developer how to upload mods if it is not a source game, but if it is a source game, to use their guide on how to upload.


texts:
Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace BreakOut
{
    class Field
    {
        public static Field generateField()
        {

            List<Block> blocks = new List<Block>();
            for (int j = 0; j < BlockType.BLOCK_TYPES.Length; j++)
                for (int i = 0; i < (Game1.WIDTH / Block.WIDTH); i++)
                {
                    Block b = new Block(BlockType.BLOCK_TYPES[j], new Vector2(i * Block.WIDTH, (Block.HEIGHT + 2) * j + 5));
                    blocks.Add(b);
                }

            return new Field(blocks);
        }

        List<Block> blocks;
        public Field(List<Block> blocks)
        {
            this.blocks = blocks;
        }

        public void Update(GameTime gameTime, Ball b)
        {
            List<Block> removals = new List<Block>();
            foreach (Block o in blocks)
            {
                if (o.BoundingBox.Intersects(new Rectangle((int)b.pos.X, (int)b.pos.Y, Ball.WIDTH, Ball.HEIGHT)))   //collision with blocks
                {
                    removals.Add(o);
                }
            }

            foreach(Block o in removals)
                blocks.Remove(o);           //removes the blocks, but i need help hitting one at a time
        }

        public void Draw(GameTime gameTime)
        {
            foreach (Block b in blocks)
                b.Draw(gameTime);
        }
    }
}

I'm trying to add collision so that when the ball hits against a block, then one of the blocks disappears.

The problem I'm having is: When the ball hits the block, it removes them all in one instance.


texts: Creating Rectangle-based buttons with OnClick events

texts:
As the title implies, I want a Button class with an OnClick event handler. It should fire off connected events when it is clicked.

This is as far as I've made it:

public class Button {

    public event EventHandler OnClick;

    public Rectangle Rec { get; set; }
    public string Text { get; set; }

    public Button(Rectangle rec, string text) {
        this.Rec = rec;
        this.Text = text;
    }

}

I have no clue what I'm doing with regards to events. I know how to use them but creating them myself is another matter entirely. I've also made buttons without using events that work on a case-by-case basis.

So basically, I want to be able to attach methods to the OnClick EventHandler that will fire when the Button is clicked (i.e., the mouse intersects Rec and the left mouse button is clicked).


texts: Combining lots of small polygons to one (some) big poly(s)

texts:
I am looking for algorithm to merge lots of relatively small 2d polygons to one or some big polygons. In case two small polygons are touching or overlapping, they should be merged to one polygon.

My big goal is to sufficiently decrease amount of points/lines required to describe collider. Resulting collider can include some polygons, btw.

Could you propose an algorithm or library to do this? (Finally I will implement solution in C# for Unity3d).

P.S. Here is one picture of task I need to solve. Look this http://epsiloncool.ru/i/E20160624-224050.png Green lines is a colliders. I need to merge them all to get one collider (or some)


texts: Correcting for a collision overlapping too much?

texts:
I have a TileMap with a TileMapCollider2D and a Sprite with a BoxCollider2D. I'm not using physics at all so I'm correcting for the collision on my own. Here's my attempt:

void FixedUpdate() {
    float h = Input.GetAxis("Horizontal") * Time.deltaTime * this.Speed;
    float v = Input.GetAxis("Vertical") * Time.deltaTime * this.Speed;
    Vector3 pos = this.transform.position;
    pos.x += h;
    pos.y += v;

    foreach (Tilemap map in this.Maps) {
        TilemapCollider2D mapc = map.GetComponent<TilemapCollider2D>();
        ColliderDistance2D dist = this.boxCollider.Distance(mapc);
        if (dist.isOverlapped && dist.isValid) {
            Debug.DrawLine(dist.pointB, dist.pointA, Color.white);
            Vector2 correction = dist.normal * dist.distance;
            pos += (Vector3)(correction);
        }
    }

    this.transform.position = pos;
}

This logic is on the blue square in this gif:

According to the documentation, dist.normal * dist.distance should be exactly the distance and direction required to make the two colliders touch. However you can see that I can push a few pixels into the red walls. When I release the button it takes several frames to back out of the wall. It goes a little haywire too when I go diagonally into the corner.


texts: How much do inconsistencies in update timing matter?

texts:
Yesterday I wrote my first game loop with fixed timesteps.
It is supposed to run every 50 ms, however it runs at 50-53 ms.
Does it matter?

I'm guessing no, but I figured I would ask anyway.

startTime = std::chrono::high_resolution_clock::now();

while(running == true){

    updateTime = std::chrono::high_resolution_clock::now();

    deltaTime = std::chrono::duration_cast<std::chrono::milliseconds>(updateTime - lastUpdateTime).count();
    lag += deltaTime;

    eventChecker();
    keyboardManager();

    while(lag >= MS_PER_UPDATE){
        update();
        lastUpdateTime = updateTime;
        //cout << lag << "|";
        lag -= MS_PER_UPDATE;
    }

    render(lag / MS_PER_UPDATE);

}


texts: Seaming between procedurally generated terrain meshes in Unity

texts:
I have been generating procedural terrain for an upcoming project however I am coming across a seaming effect between the tiles:

I have searched for solutions including this video.

Here is the code (sorry for the lack of comments):

chunkx and chunky are the x and y coordinates of the chunk that is being generated.

seed is a randomly generated integer.

float Gen_Height(int x, int y, int seed)
{
    float height = 0;
    float newx;
    float newy;
    for (float resolution = 128; resolution >= 8; resolution /= 8)
    {
        newx = (seed / 40f) / resolution + x / resolution;
        newy = (seed / 40f) / resolution + y / resolution;
        height += (Mathf.PerlinNoise(newx, newy) - 0.5f) * resolution;
    }
    if (height < 0) height = 0;
    return height;
}

public List<Vector3> Gen_Vertices(int chunkx, int chunky, int seed)
{
    float height;
    int x = 101;
    List<Vector3> vertices = new List<Vector3>();

    for (int i = 0; i < x; i++)
    {
        for (int j = 0; j < x; j++)
        {
            height = Gen_Height(i + chunkx * (int)x, j + chunky * (int)x, seed) * heightmod;
            vertices.Add(new Vector3(2*i, height,2* j));
            if (height > maxheight) maxheight = height;
            else if (height < minheight) minheight = height;
        }
    }
    return vertices;
}


texts:
As we know, tiles can make it quicker to update large portions of the display at once, as compared with a bitmap. To put, say a letter, on the screen, the Commodore 64 typically does two writes (the screencode and the attribute), but the ZX Spectrum typically does 9 (eight bytes which make up an 8x8 bitmap, plus 1 for the attribute).

Recently, a demo for the SEGA Genesis was released called Red Eyes. My understanding is that the 3D scenes were rendered on a PC, and some kind of program converted these animations to a tileset so that each frame can quickly be written into VRAM.

But, however hard I search I cannot find any contemporaneous games for these retro systems which use a tileset to render (an approximation of) three-dimensional graphics. So is there a technical reason for that?

The nature of this question is such that it could be answered in the following ways:

It wouldn't work because ...
You obviously weren't looking hard enough because here's an example of a game that does that. Here's a disassembly or source code so you can figure out how it worked
It might be possible, but you'd have to watch out for ...


texts: Platformer collision detection problem - player snapping onto sides

texts:
I am having problems with collision detection. I am trying to make a simple platformer but when the player is falling or moving too fast it sometimes detects the wrong collision side. I am getting the side of the collision by checking the distance between the player and the sides of a block that are exposed to the player. I also tried detecting collision one axis at a time but this glitch still occurs.

blockCollision: function(block) {
        if(this.x + this.width > block.x && this.x < block.x + block.width && this.y + this.height > block.y && this.y < block.y + block.height) {
            let distanceLeft = Math.abs(this.x + this.width - block.x)
            let distanceRight = Math.abs(this.x - (block.x + block.width))
            let distanceTop = Math.abs(this.y + this.height - block.y)
            let distanceBottom = Math.abs(this.y - (block.y + block.height))

            if(distanceLeft < distanceTop && distanceLeft < distanceBottom && !block.collisionSides.includes('L')){
                this.velX = 0
                this.x = block.x - this.width
            }
            if(distanceRight < distanceTop && distanceRight < distanceBottom && !block.collisionSides.includes('R')){
                this.velX = 0
                this.x = block.x + block.width
            }
            if(distanceTop < distanceLeft && distanceTop < distanceRight && !block.collisionSides.includes('T')){
                this.jumping = false
                this.velY = 0
                this.y = block.y - this.height
            }
            if(distanceBottom < distanceLeft && distanceBottom < distanceRight && !block.collisionSides.includes('B')){
                this.velY = 0
                this.y = block.y + block.height
            }

            if(distanceLeft == distanceTop && !block.collisionSides.includes('LT')){
                this.x = block.x - this.width
                this.y = block.y - this.height
            }
            if(distanceLeft == distanceBottom && !block.collisionSides.includes('LB')){
                this.x = block.x - this.width
                this.y = block.y + block.height
            }
            if(distanceRight == distanceTop && !block.collisionSides.includes('RT')){
                this.x = block.x + block.width
                this.y = block.y - this.height
            }
            if(distanceRight == distanceBottom && !block.collisionSides.includes('RB')){
                this.x = block.x + block.width
                this.y = block.y + block.height
            }
        }
    }

JsFiddle


texts: Creating Complex Collision Shapes in GMS2

texts:
I'm pretty new to Game Maker Studio 2 and I've hit a wall in programming with their built-in physics engine. I created a irregularly shaped object and I want to modify the collision shape so that it fits the shape of the sprite. In the built in collision shape editor it only allows you to create a convex shape with a max of 8 points. Is there another way to do this without having to plot out points individually in code?

Thanks!


texts: What is Unity NetworkTransport message encoding and signature

texts:
I'm new to exciting world of Unity, and I have problem establishing network connection using NetworkTransport API.

I'm using NodeJS as server. And I have some questions.

Does NetworkTransport.Connect method awaits some response message from
server?
What is the encoding and message signature of Connect,
Disconnect, Send and Receive methods?

My client's code so far:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class Network : MonoBehaviour {

private int unreliableChannel;
private ConnectionConfig config;
private HostTopology topology;
private int hostId;
private int connectionId;
private byte error;

void Start () {
    NetworkTransport.Init();
    config = new ConnectionConfig();
    unreliableChannel = config.AddChannel(QosType.Unreliable);
    topology = new HostTopology(config, 1);
    hostId = NetworkTransport.AddHost(topology, 4444);
    connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", 3051, 0, out error);
    Debug.Log(connectionId);
}

void Update () {
    int recHostId;
    int connectionId;
    int channelId;
    byte[] recBuffer = new byte[1024];
    int bufferSize = 1024;
    int dataSize;
    byte error;
    NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
    switch (recData)
    {
        case NetworkEventType.Nothing:
            break;
        case NetworkEventType.ConnectEvent:
            break;
        case NetworkEventType.DataEvent:
            Debug.Log("Message: " + System.Text.Encoding.Unicode.GetString( recBuffer, 0, dataSize ) );
            break;
        case NetworkEventType.DisconnectEvent:
            break;
    }
}

}

Server part looks like this

const dgram = require( 'dgram' );
const server = dgram.createSocket( 'udp4' );

server.on( 'listening', () => {
    let address = server.address();
    console.log( 'UDP Server listening on ' + address.address + ":" + address.port );
});

server.on( 'message', function ( message, remote ) {
    console.log( remote.address + ':' + remote.port +' - ' + message.toLocaleString('utf8') );
    server.send(Buffer.from('hello'), remote.port, remote.address, function ( err, bytes ) {
        if ( err ) {
            throw err;
        }
        console.log( `${bytes} bytes sent` );
    });
});

server.bind( 3051, '127.0.0.1' );

Problem is that on server I receive message that I can't decode it. (some strange binary symbols remain). Also, when I'm sending something to client, NetworkTransport.Receive() receives nothing.
Thank you.


texts: This is the first time I'm using libgdx and I've got one problem. I am confused by the web of dependencies and the number of projects and I'm not sure how and mostly where to add a third party library I want to use. It should work both for desktop and android. How is this done?


texts: Are unity games as performant as Unreal's?

texts:
TLDR: I make both RPG and MMORPG, 3D, heavy games with big landscape. Both engines are very good, but which one produces games with more FPS assuming the quality was the same?

I've been using RPGmaker and Gamemaker a lot in the past.

Recently I've kept switching from UE4 to Unity and vice versa. I can't decide which one is better. Unity is more popular so its a huge + for unity.

However some people claim Unreal games are much faster because unreal codes in c++.

However, Unity now created something called DOTS thats supposed to be faster than c++

For example, this site says that Unity is better than ue4 especially for rpg, which is one of my fav genres

What are your thoughts? I need to know this to not spend months and years in wrong engine.


texts: Scene Graphs and Entity Component Systems

texts:
I am trying to determine how to move my current implementation of nodes in a scene graph to an entity component system and am struggling to wrap my head around how the two can work together, if at all.

I think the main cause of my confusion is breaking the habit of structuring everything in an object oriented hierarchy. I'm not overly familiar with game development as a whole so breaking what I already know works to replace with something else will be a testament to my knowledge.

Currently, I have a scene controller and a scene which handle the update and render loops accordingly. Code removed for brevity.

//scene controller
- (void)update:(NSTimeInterval)duration
{
    //loop though objects and integrate
}

- (void)render
{
    [[self scene] render];
}

//scene
- (void)render
{
    //loop through objects and render
}

This works fine with my scene nodes as is. Each node has properties for position, rotation, scale and geometry which are passed to shaders and rendered.

Now I am trying to remove all of these properties from the node and replace them with components.

Note: I realise that node means something else in an Entity Component System so this will be refactored into something else entirely.

It is my understanding that once I have transitioned from the current implementation to an ECS my game objects will expose the same position, rotation, scale and geometry properties but via components instead.

As of such, where will these new game objects sit in the hierarchy of a scene graph? My first thoughts would be to refactor the update and render loops to include the appropriate systems, a la:

//scene controller
- (void)update:(NSTimeInterval)duration
{
    //loop though objects and integrate
    [[self positionSystem] update:duration];
}

- (void)render
{
    [[self scene] render];
}

//scene
- (void)render
{
    //loop through objects and render
    [[self renderSystem] render];
}

However, it would seem odd to have the systems spread across two different objects (the scene controller and the scene). It would be possible remove the scene render loop and do this in the scene controller instead to keep everything in one place.

One final cause of confusion is how to link game objects together in the same way that my nodes are currently setup. A node can have children and a parent node which combine the parent matrices up the chain to allow me to link objects together, i.e.: a player and a sword.

From what I can gather, objects in an ECS shouldn't be linked together in this same way, or have I misunderstood the principles of an ECS? If this is the case, how would you create a scene graph from entities that aren't linked together in any way?

I'm eager to step back from my current implementation and overhaul the necessary parts but I'm not sure how to achieve a similar setup or if it is possible or even the correct way of doing things.


texts:
I want to move my bodies at higher speeds, but they have a top speed.

I have an Ortoghraphic camera defined at 800x480.
My world doesnt have gravity.
I apply an impulse of 1000,and a force of 1000 too.

But the speed always is at the same value, it doesnt have more.

How do i add more speed to my body (its a dynamic body).


texts: Why is there no glClear() and glClearColor() method in GL30?

texts: In the GL30 interface, both the methods glClear() and glClearColor() are absent. I tried to call the method Gdx.gl30.glClear(GL30.GL_COLOR_BUFFER_BIT) inside render() but it threw me a null pointer exception. So I checked the interface. There's no glClear() method in GL30. Only in GL20. But OpenGL documentation says that they are supported in both v2.0 and v3.0. Why is it not included in LibGDX?


texts:
I want to be able to destroy and deform a car in-game.

For example, I want two cars to crash and a) break the meshes apart (probably applying force to fly them apart) and b) deform the mesh (like bending the side doors).

How would I go about this?

Thank you in advance.


texts: How to get the height at a position in a triangle

texts:
I have a heightmap, and I store the heights in a giant array.  However, when I move, it's quite choppy on the Y-axis, so I need a way to get the height at a certain point in a triangle.

I currently am picking a triangle based on the player's position, but I'm stuck on finding the intermediate height at the point.  At the moment, I'm using similar triangles on each axis to calculate the height, but this method seems slow, and someone mentioned using a weighted average to find the height, which would probably be faster.

I know that DirectX has a "D3DXIntersectTri" function, but I couldn't find one in XNA.

Basically, I just want to know how the height is interpolated with a weighted average.\

Thanks!


texts: Game Architecture and Separation of Concerns

texts:
I'm trying to build a "simple" Tetris game, but I want to have enough flexibility to add a few things:

The game can be played by a human, or (if the human presses a certain key) an AI is swapped in.
The rendering code should be "configurable". That is, the user may enable or disable animations, or speed them up.

MVC initially looks like a good fit: the game itself is encapsulated in a Game object, providing some methods to interact with it (moveLeft, rotate). The Controller would handle user input or AI. The View just renders the game, and gets notified of updates by the Game itself whenever something interesting happens (PieceMoved, LineDestroyed and so on).

However, my problem mostly lies in "What if I want a blocking animation?"

When lines are destroyed, I want to do a "falling" animation where the top lines crush the bottom lines (or whatever), but since this animation may take some time, I want to avoid updating the game (that is, piece gravity) until the animation is completed.

Does it make sense to have the Controller do something like...

void update() {
    input.process()
    render.update()
    if (!render.blocked()) {
        game.update();
    }
}

Is MVC a bad fit for this? What's a good way to separate concerns in games?

(I am using libGDX, but my question isn't limited to it.)


texts: Problem with bounding box in model space and intersection with ray

texts:
I have a bounding box in model space and I want to intersect it with a ray. I have tried to transform the ray like this. Rotating and scaling works well, but transition does not.

Here is my code:

Xbouding = new BoundingBox(new Vector3(50, 10, 10), new Vector3(120, -10, -10));

ray.Position = Vector3.Transform(ray.Position, Matrix.Invert(MathUtil.CreateWorldMatrix(Position, Rotation, Scale)));
ray.Direction= Vector3.Transform(ray.Direction, Matrix.Invert(MathUtil.CreateWorldMatrix(Position, Rotation, Scale)));
float? dist = ray.Intersects(Xbouding);

I have this:

I want to know if the ray from the mouse intersects with the boxes shown in the image. Pick works fine unless the model is translated (rotating and scaling works).

Another little question: what does float? mean? What's the difference between float and float??


texts:
I have been experimenting with 2D Simplex noise for a mini-project and while I cannot say I understand the maths behind it, I begin to feel quite confident with how I can manipulate it to get different types of output.

While noise generation/algorithms/manipulation are quite easy to find, I am having trouble finding any good resources on the next step, i.e. placing 2D tiles based on the noise output (for the purpose of making some kind of 2D terrain).

I realize a crude and simple way would be to just loop through my array and place a tile on every coordinate where the noise value is above a certain point, but the output would look very rough, tiles would be overlapping each other, etc.

Does anyone have any good resources or information to share on this subject?

Thanks,


texts: How to manage instances of (placed) cards and decks in card games?

texts:
This question sounds quite specific, but I mean in general, how do you manage something like a card game when it comes to decks (one for player1, one for player2, ...) and placed cards focused on instances of a Card-object?

Specifically in my case - using Java - I got a few cards with static data (image, values displayed on them, ...) and some data, depending on who has the card in their deck or where it lies on the board, for each type of card.

Now I got instances of those cards with their values like

Card DOG = new Card(image, a, b, ...);
Card SHEEP = new Card(image, a, b, ...);
Card PIG = new Card(image, a, b, ...);

statically in Card. Maybe this is already the wrong way to do it?

How do I manage decks and stuff now, because I need specific instances after those blueprints, but fitted to their use, be it the deck where it is in or if it is on hand or on board, ...

The first thought I got was having something like Card.createInstance but is this something that is done?

I'm more or less asking for a best practice on doing something like this.


texts: Chromium Embedded Framework and Unity3D?

texts:
I have recently heard about the Chromium Embedded Framework and was over-joyed as I want to use html as my GUI source.

I did find a C# version but it seems to be for Windows Forms.

I'm not too terribly well versed but I was under the impression that it may cause it to be unavailable for cross-platform use.

Can anyone provide and insights? And if this will not work, any free alternatives?


texts: Changing an Image's alpha through an animation in Unity

texts:
I'm trying to change an Image's alpha through a legacy animation in Unity, so that it fades in and out in a loop. The animation works: I can see the color updated in realtime in the inspector. But the Image is not actually being updated. I know that it is possible this way, since changing the alpha manually in the inspector does change the opacity of the Image.

I could write a script for this, but would prefer to do it through an animation.


texts: Use GKEntity's component(ofType:) with inheritance

texts:
I'm writing a SpriteKit game in swift and making use of GameplayKit's entity-component system. There are many components that do different stuff but share the same methods in which they do it, so I thought I'd group them into categories. At first I thought about using protocols, but component(ofType:) only accepts classes. So then I thought about making a base class for each category, define methods and variables there and have the actual components classes override them to implement their own functionality (you know like basic OOP). So I had something like:

class InputComponent: GKComponent {
    func handleInput() {
        //Whatever
    }
}

class ControllerComponent: InputComponent {
    override func handleInput() {
        //Do something
    }
}

class KeyboardComponent: InputComponent {
    override func handleInput() {
        //Do something different
    }
}

Then somewhere in my code I'd call

entity.component(ofType: InputComponent)

and I thought I'd get both ControllerComponent and KeyboardComponent type objects. But I am getting none, it seems component(ofType:) doesn't return instances of subclasses.

I guess I can make an extension to GKEntity and define something like

component<P>(conformingTo protocol: P.Type)

and implement that behavior myself but I want to know if I can use the built in function to achieve the same.


texts: How to implement ECS in a videogame with C++?

texts:
What do I need to know in order to implement ECS in a video game? I'm developing a video game and so far I wasn't using any complete architecture, I was just using inheritance but I don't like it because the code became messy.
So far, I've seen so many articles in which the subject is treated, but I don't understand how to implement it. All what I get is there is that a component is a bunch of information, an entity is a bunch of components, and each system deals with the logic of its own components. But I've got a question about it, they're a bunch of IDs, how do those IDs store data? How to retrieve data from it? I've got a problem, since I was trying to implement components, in order to do it all what I did was declare a parent abstract class in which I'd store members of that class and then I would be able to access to those members. The problem came when I was trying to declare children of that abstract class, since that parent class can't have all the members of all the another components (and I need a way to iterate all the components in a vector).
So... I want to keep the things as simple as possible. Any advice for someone like me? How can I implement ECS in a simple platformer?
Please, Thanks in advance!


texts:
Currently I am working on a project in which I generate geometry based on the players movement. A glorified very long trail, composed of quads.

I am doing this by storing a STD::Vector, and removing the oldest verticies once enough exist, and then calling glDrawArrays.

I am interested in switching to a shader based model, usually examples I see the VBO is generated at start and then that's basically it. What is the best route to go about creating geometry in real time, using shader / VBO approach


texts: Snake game - collision detection causing new position of apple to be rendered multiple times

texts:
I have a collision method implemented through the use of slick2d. When ever the snake collides with the apple, it causes the apple to be rendered in multiple places before the snake moves further along.

    if(checkCollision() == true){
        x -= 1;

        snakes.add(new Point(x, y));
        locateApple();
    }

And heres the locate method to move the apple in a random position:

public void locateApple() {
       int r = (int) (Math.random() * RAND_POS);
       applePoint.setX((r * DOT_SIZE));
       applePoint.setY((r * DOT_SIZE));

   }

This is in my update() method, which is probably causing the problem, how can I run this code only once? SO that once it collides, it moves the apple in a new position with out executing multiple times.


texts:
I have a function in which I'm looping y and x over my array of sprites. That's a lot of loops, and it is very slow; I'd like to improve the performance.

I would like to only have to build the surface once, calling a buildMap method at the start, and referencing the resulting surface each time I need to blit it without having to loop to find the correct sprite and position.

int aff_map(t_exe *exe)
{
    int         sprite_idx;
    int         y, x;
    SDL_Rect    srcrect, dstrect;

    dstrect.y = 0;
    srcrect.y = 0;
    srcrect.w = TILE;
    srcrect.h = TILE;

    for (y = 0; y < HEIGHT; y++)
    {
        dstrect.x = MARGE_X;

        for (x = 0; x < WIDTH; x++)
        {
            for (sprite_idx= 0; sprite_idx< NB_TILES; sprite_idx++)
            {
                if (exe->map[y][x] == g_assoc_map[sprite_idx].key)
                      srcrect.x = g_assoc_map[sprite_idx].idx * TILE;
                if (SDL_BlitSurface(exe->sprite, &srcrect, exe->screen, &dstrect)
                        < 0)
                    return (err_sdl(SDL_GetError()));
            }

            dstrect.x += TILE;
        }

      dstrect.y += TILE;
    }

  return (EXIT_SUCCESS);
}

Is it possible to build an SDL_Surface before blitting it?


texts: 2D to 3D perlin noise, I'm not sure I get it

texts:
I've been using 2d perlin noise to generate height maps for a little isometric terrain experiment. The noise value is directly related to the z-layer a tile will appear in: Math.floor(noise * 10). Perlin is great but height is now always linear and I'm not sure how to change this.

One thing I tried was making the height value go up exponentially, producing a map akin to the image attached. Now my maintains are larger and more interesting looking, but this obviously produces gaps. I'm not sure how to "pad" or 3D-ify those layers. Any pointers?

    var diff = .04;
    var zz = Math.random() * 100;
    var x, y, xx, yy;

    for (var y = 0; y < maxY; y++) {
        this.grid[y] = new Array(maxX);
        for (var x = 0; x < maxX; x++) {
            xx = 0 + x * diff;
            yy = 0 + y * diff;

            this.grid[y][x] = Math.floor(Math.pow(simplex.noise(xx, yy, zz) * 4), 2.3));
        }
    }
    return this.grid;

edit:
i'm sorry i'm not more clear. i'm not entirely sure what i'm asking because i'm not entirely understanding the maths. the terrain i've been trying to make starts at the base level with water. then some layers of grassy types, going into mountains. i'm not building minecraft here, i don't intend to dig around in it, but i would like to be able to rotate it sometime (replacing the tiles with cubes). right now, simplified, i'm expressing x and y as a 2d grid, with the value representing z, like so. z is really just my tile height.

var grid = [
    [1,1,1],
    [1,3,1],
    [1,1,1]
]

in this example i will draw 9 tiles, with the middle one at a height of 3 creating the gaps you see in the image. i was thinking the image would be more complete if this was a 3d grid.

var grid = [
    [
        [1,1,1],
        [1,1,1],
        [1,1,1],
    ],
    [
        [ , , ],
        [ ,2, ],
        [ , , ],
    ],
    [
        [ , , ],
        [ ,3, ],
        [ , , ],
    ]
]

blanks in this case will not be drawn. the values in the array could represent the type of tile for instance. i tried this with 3D noise but i'm very unsure how to interpret the density values (from -1 to 1). Drawing all density values under 0 (as the same tile) got me the image below which is cool, but not what i was hoping for. So far everything i've read about this does not explain what the values actually mean. translating the density values into into 'types' of terrain generates mostly nonsense, with random bits of water all over the place. the whole thing just looks like a giant cube with holes in it.

maybe i'm not making sense because what i want does not make sense, this is entirely possible. the internets is letting me down and i'm hoping some smart people can point me in the right direction.


texts:
I'm quite new to working with 3D objects.  I'm currently trying to get one to load in Monogame.  The object itself was imported into Blender and exported as an fbx file (which was the only file type I could get the new content pipeline to work with).

The command to load the model is here:

var _model = content.Load<Microsoft.Xna.Framework.Graphics.Model>("Ship");

And the code to draw it is:

public override void Draw(IDrawParameters p)
{
    // Copy any parent transforms.
    Matrix[] transforms = new Matrix[_model.Bones.Count];
    _model.CopyAbsoluteBoneTransformsTo(transforms);

    // Draw the model. A model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in _model.Meshes)
    {
        // This is where the mesh orientation is set, as well
        // as our camera and projection.
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationX(_modelRotation) *
                Matrix.CreateRotationY(_modelRotation);
            effect.View = Matrix.CreateLookAt(eye, Vector3.Zero,
              Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
              MathHelper.ToRadians(45.0f), _aspectRatio, 1.0f, 10000.0f);
        }
        // Draw the mesh, using the effects set above.
        mesh.Draw();
    }
    base.Draw(p);
}

I've tried a number of variations of the draw code, mostly taken from the web.  However, whatever I try, I get nothing appearing on the screen - no error, but nothing on the screen.

Is there anything specific in the code below that might cause this; or, is there a possibility that the content.Load didn't work, but it just didn't tell me?

UPDATE

More than one of the answers below are correct in my case.  The first problem that I had was the transform:

effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationX(_modelRotation) *
                Matrix.CreateRotationY(_modelRotation);

The second issue was with the Alpha flag; both of these together made it show, but only because I'd written a routine to change the eye position - the original rendering was inside the object.


texts: Should my GLSL Shader object/wrapper encapsulate loading/setting a VertexArrayObject?

texts:
I am working on a 2D game in C++, with a simple rendering layer over OpenGL.

I have a wrapper for GLSL shaders and shader programs, these wrappers encapsulate shader objects into C++ classes and automatically handle loading/compiling/linking and using shader programs.

VertexArrayObjects, it seems to me, are basically a collection of configuration settings to use with a particular ShaderProgram.

My question is: Should I encapsulate VAO's within my ShaderProgram objects, or within the Sprite objects? Does a VAO change on a per-shader basis or do I need a new VAO for every type of drawable object? If the latter, do I need one VAO to draw all Sprites (each containing 4 vertices, a position/orientation etc), or one VAO per sprite object in the game?


texts: HTML5 or Javascript game engine to develop a browser game

texts:
I would like to start developing a MMO browser game, like Travian or Ogame, probably involving also a bit of more sophisticated graphical features such as players interacting in real time with a 2d map or something like that.

My main doubt is what kind of development tools I should use: I've a good experience with PHP and MySQL for the server side and Javascript (and jQuery) regarding the client side. Coding everything from scratch would be of course really painful so I was wondering if I should use a javascript game engine or not. Are there (possibly free) game engine you would recommend? Are they good enough to develop a big game?

Also, I saw a lot of HTML5 games popping up lately but I'm now sure if using HTML5 is a good idea or not. Would you recommend it? What are the pro and cons about using HTML5? If you'd recommend it, do you have any good links regarding game development with HTML5?

(PS: I know that HTML5 and a Javascript engine are not mutually exclusive, I just didn't know how to formulate a proper title since English is not my main language. So, please, answer addressing HTML5 and a game engine pro and cons separately)


texts: Creating texture and palette modification

texts:
I need to create a texture from a surface with indexed color palette and alter the colors. However, after I set new colors, the rendered texture gets blank.

int main(int argc, char** argv)
{
    init();

    gSurface = TTF_RenderText_Solid(gFont, "text", fg1);

    // text is rendered properly, without following line
    SDL_SetPaletteColors(gSurface->format->palette, &fg2, 1, 1);

    gTexture = SDL_CreateTextureFromSurface(gRenderer, gSurface);

    SDL_SetRenderDrawColor(gRenderer, 255, 255, 255, 255);
    SDL_RenderClear(gRenderer);

    SDL_RenderCopy(gRenderer, gTexture, NULL, NULL);
    SDL_RenderPresent(gRenderer);

    SDL_Delay(1000);

    quit();
}

I tested this code with software rendering using window surface instead of renderer and pallete changing worked.
Could someone explain me why does it happed and how to fix it?


texts: Cumulative transformation matrices for hierarchical object transformations

texts:
I'm having a small issue with my design for hierarchical 3D objects. I'll try to sum things up concisely. Every object has a vector3 for its position, scale, and rotation, as well as a std::vector of children objects. An object's render function takes an optional parameter for a parent's transformation matrix, which defaults to the identity matrix. In this render function, the object's transformation matrix is computed with this form:

transformation = parentTransformation * translationMatrix * rotationMatrix * scaleMatrix;

After the matrix is computed, all of the childrens' render functions are called with the computed matrix being passed, then the actual render for THIS object happens.

My problem seems to be with the scaling bit. For this case, I have a wooden manikin built out of several spheres, all translated and scaled to give shape. For the legs and arms, I scaled the sphere pieces obviously not uniformly. To avoid the children objects of those body parts from also being scaled like that, I scale them by the inverse of that scale factor after scaling the particular body part. However, when I rotate a joint which is a child of one of these oddly scaled pieces, you can see how the scaling is really only in the childrens' "model space" and as a result, they get strangely contorted. Is there a misunderstanding on my part about how objects should inherit their parents' transformations?

Here are some images to demonstrate my results. The second image is after rotating the knee joint 80 degrees.


texts: Best algorithm for recursive adjacent tiles?

texts:
In my game I have a set of tiles placed in a 2D array marked by their Xs and Zs ([1,1],[1,2], etc).

Now, I want a sort of "Paint Bucket" mechanism: Selecting a tile will destroy all adjacent tiles until a condition stops it, let's say, if it hits an object with hasFlag.

Here's what I have so far, I'm sure it's pretty bad, it also freezes everything sometimes:

void destroyAdjacentTiles(int x, int z) {
    int GridSize = Cubes.GetLength(0);
    int minX = x == 0 ? x : x-1;
    int maxX = x == GridSize - 1 ? x : x+1;
    int minZ = z == 0 ? z : z-1;
    int maxZ = z == GridSize - 1 ? z : z+1;

    Debug.Log(string.Format("Cube: {0}, {1}; X {2}-{3}; Z {4}-{5}", x, z, minX, maxX, minZ, maxZ));

    for (int curX = minX; curX <= maxX; curX++) {
        for (int curZ = minZ; curZ <= maxZ; curZ++) {
            if (Cubes[curX, curZ] != Cubes[x, z]) {
                Debug.Log(string.Format("        Checking: {0}, {1}", curX, curZ));
                if (Cubes[curX,curZ] && Cubes[curX,curZ].GetComponent<CubeBehavior>().hasFlag) {
                    Destroy(Cubes[curX,curZ]);
                    destroyAdjacentTiles(curX, curZ);
                }
            }
        }
    }
}

Update: I'm trying the recursive version of the Flood-fill algorithm, but I'm having trouble. In order to check the west adjacent tile, I use x-1, for the east, x+1 etc. Problem is, as soon as x = 0, it will infinitely loop between 0 and 1. I also have to check that that tile exists, so I'm using ifs to figure it out in order to not get an IndexOutOfRangeException (I tried using try/catch, but it's pretty much the same result, I figured this would be simpler). Here's my code right now (yes, I'm reproducing mineSweeper):

bool destroyAdjacentTiles(int x, int z) {
    int GridSize = Cubes.GetLength(0);
    int minX = x == 0 ? x : x-1;
    int maxX = x == GridSize - 1 ? x : x+1;
    int minZ = z == 0 ? z : z-1;
    int maxZ = z == GridSize - 1 ? z : z+1;

    Debug.Log(string.Format("Cube: {0}, {1}; X {2}-{3}; Z {4}-{5}", x, z, minX, maxX, minZ, maxZ));

    CubeBehavior thisCube = Cubes[x, z].GetComponent<CubeBehavior>();

    if (thisCube.isMine) { Destroy(thisCube); Cubes[x,z] = null; return false; } // TO DO: Make this = game over
            // BELOW: Always, no matter what, causes the object to destroy, dunno why. So I removed it for the time being.
    //if (thisCube.surroundingMines >= 1) Destroy(thisCube); return true;

            // if the function doesn't return by now, means it's a to-be-destroyed cube, so destroy it
    //Destroy(thisCube.gameObject);
    //Cubes[x,z] = null;

            //
    if (x > 0) {
        if (Cubes[x-1,z].gameObject) destroyAdjacentTiles(x-1, z);
        if (x < GridSize - 1)
            if (Cubes[x+1,z].gameObject) destroyAdjacentTiles(x+1, z);
    }
    if (z > 0) {
        if (Cubes[x,z-1].gameObject) destroyAdjacentTiles(x, z-1);
        if (z < GridSize - 1)
            if (Cubes[x,z+1].gameObject) destroyAdjacentTiles(x, z+1);
    }

    return true;
}


texts:
I have been looking at tile engines for the past few days and decided to have a go at my own one for educational purposes. I want to use different textures for the tiles of my map, for example 1 = grass, 2 = sky, 3 = dirt etc.. I am having this problem where the tiles will draw using only one specific texture although I provide multiples. I have been following tutorials here and there and searching online to try and find this problem but to no avail.

In the example below in the LoadContent function I load three different textues into my TileMap object and Console.WriteLine states that there actually are 3 textures loaded into the list.

I was under the impression that the draw method in the TileMap would set the index to the tile ID corresponding to a tile texture and then that specific tile would be drawn on the map in game. for example, index 1 would equal the first texture in the list, index 2 would equal the second texture and so on.
Is this a correct assumption or am I way off?

Also, can you give me any help/pointers on ways to fix this issue of only one texture showing on the screen.

Thank you in advance.

Tile Map

 class TileMap
    {
        private MapCell[,] mapCell;
        public const int TILE_WIDTH = 64;
        public const int TILE_HEIGHT = 64;

    private List<Texture2D> tileList = new List<Texture2D>();

    public TileMap(int[,] exisitingMap)
    {
        //initialise this to a new multidimensional array;
        mapCell = new MapCell[exisitingMap.GetLength(0), exisitingMap.GetLength(1)];
        // x always starts on one
        for (int x = 0; x < mapCell.GetLength(1); x++)
        {
            for (int y = 0; y < mapCell.GetLength(0); y++)
            {
                mapCell[y, x] = new MapCell(exisitingMap[y, x]);
            }
        }
     }

    public void loadTextureFiles(ContentManager content, params string[] fileNames)
    {
        Texture2D tileTexture;
        foreach (string fileName in fileNames)
        {
            tileTexture = content.Load<Texture2D>(fileName);
            tileList.Add(tileTexture);
            Console.WriteLine(tileList.Count + " Tile texture count ");
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {

        for (int x = 0; x < mapCell.GetLength(1); x++)
        {
            for (int y = 0; y < mapCell.GetLength(0); y++)
            {
                // setting the index to the tile ID
                int index = mapCell[y,x].TileID;
                Texture2D texture = tileList[index];

                spriteBatch.Draw(texture, new Rectangle( x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT), Color.White);

            }
        }
    }
}

Map Cell

class MapCell
{
    public int TileID { get; set; }

    public MapCell(int tileID)
    {
        tileID = TileID;
    }
}

Game1

TileMap tileMap = new TileMap(new int[,]
    {
        { 0,0,0,0,0,0,0 },
        { 1,1,1,1,1,1,1 },
        { 0,1,1,2,1,1,1 },
        { 0,2,1,3,1,3,0 },
        { 0,3,0,3,0,0,0 },
        { 0,0,0,2,0,0,0 },
        { 0,0,0,1,0,1,0 },
    });

 protected override void LoadContent()
    {
        new SpriteBatch(GraphicsDevice);
        tileMap.loadTextureFiles(Content, "Tiles/Tile1", "Tiles/sky", "Tiles/dirt" );
    }

protected override void Draw(GameTime gameTime)
    {
        spriteBatch.Begin();
        tileMap.Draw(spriteBatch);
        base.Draw(gameTime);

        spriteBatch.End();
    }


texts: How can I get the normal vector for a plane from a set of vertices?

texts:
I'm working on a HLSL / C++ little project to going over my graphics work, and I am unsure how I am to get a facing vector from a vertex polygon. I can't seem to find the formula.

The positions are P1, P2,P3

Let's call them class VertexPoint with P1.x, P1.y, P1.z for example?


texts: What is a good strategy to switch my career from full-stack developer to game developer?

texts:
I am senior full-stack developer at age of 30 and I mainly work with Java EE/Spring/... in back-end and Angular/React/JQuery/... in the front-end.

I love programming but my dream job was game developer not full-stack developer. I am making good amount of money in my current position and I do not want to start from scratch again. What is a good strategy to switch my career to game-developer without a fresh start?

Update: By game-developer, I mean working on large game development companies not indie games.


texts:
I have been working on a web based game, in which involves a lot of javascript/PHP. My question is what is the most secure way to handle any data being passed between the two languages?

At this moment I am currently using javascript to preform any required functions such as making objects appear for you to click and then awarding points for clicking that object.

I know javascript isn't the best way to handle the data due to how accessible it is on the client-side. I currently use ajax to pass the points gained from a click, to PHP where it can then assess whether the points were gained fairly or by an exploit.

This works, however when it comes to making sure that the user doesn't abuse a function in the console such as "Spawning an object" I run into some issues, as I can't seem to think/find of a way to achieve this. At the moment I have it so when the game starts an interval begins which displays an object based on a random value and then when the user clicks that object it gets destroyed and their score is sent to a PHP file to check the action was legit.

Is there some sort of way I can make a checker in the PHP file to make sure that an object can only be spawned if the browser calls it and not the client. I know you can't stop a user from using the console, its more of thinking of a system to judge/evaluate whether an action is allowed by a user.


texts: How to deal with texture coordinates without range?

texts:
I have a set of given texture coordinates(u,v coordinates), but they are ranging from (-inf, inf), contradicting the [0,1] convention.

I tried to do a rescaling by
value = (value - min) / (mac - min).
But if I have a rectangle which composed of two triangles, four vertices. Suppose the u,v coordinates are

  -0.260944  0.490887
   3.619507  0.490887
   3.619507 -3.043434
  -0.260944 -3.043434

After scaling, the coordinates would be mapped to exact -1 and 1, resulting in wrong texture.

So how should I deal with this kind of texture coordinates?


texts: GL_TEXTURE_CUBE_MAP min/mag filter problem

texts:
I found it hard getting min/mag filtering to work with cubemap texture. In the screenshot-attachment I've created a cube using a cubemap texture, and also a grid of planes using a 2D texture. For both the cubemap and 2D texture I use GL_LINEAR_MIPMAP_LINEAR, for min-filter. For 2D texture it works, but for the cubemap it doesn't.

Below, I've listed the code for how I set up my cubemap texture. I would be glad if someone could help me out with this, thanks in advance :)

levels = floor(log2(max(width, height))) + 1;

glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
glGenTextures(1, &id);
glActiveTexture(textureUnit);
glBindTexture(GL_TEXTURE_CUBE_MAP, id);

glTexStorage2D(GL_TEXTURE_CUBE_MAP, levels, internalFormat, width, height);

for (GLenum target = GL_TEXTURE_CUBE_MAP_POSITIVE_X, i = 0; target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; target++, i++)
{
    glTexSubImage2D(target, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE,    cubeMapList[i]->pixels);
}

glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);


texts: Does each game asset always require a prefix such as 'spr' or 'obj' in their name?

texts:
Having started only recently with using GameMaker for game development (keep in mind that this is the first time in a long while that I'm doing something like this, so I'm technically at beginner level), I've lately been thinking about something that seems to be common place throughout creating a game with the software.

Through all the tutorials I've been through so far in GameMaker:Studio, I've noticed that the tutorials seem to want the names of game assets to always have a prefix in their names depending on what the game asset is, usually something like spr_ for sprites or obj_ for objects.

I've never exactly liked this sort of naming method, but I don't know whether or not to keep doing this or to just avoid using the prefix entirely. Does the engine require these prefixes for a game to compile or something?

Are these prefixes necessary?


texts: How do I set which side of a mesh is visible?

texts:
I know little about 3D game development, but I'm trying to understand how to set what side of a mesh has the visible face. I am using Wild Magic 5 and my object looks like this:

VertexFormat* ssVFormat = VertexFormat::Create(2,
    VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0,
    VertexFormat::AU_COLOR, VertexFormat::AT_FLOAT4, 0);
int ssVStride = ssVFormat->GetStride();

VertexBuffer* ssVBuffer = new0 VertexBuffer(8, ssVStride);
VertexBufferAccessor ssVba(ssVFormat, ssVBuffer);
Float4 ssColor(0.0f, 0.0f, 1.0f, 0.25f);
ssVba.Position<Float3>(0) = Float3(0.0f, 0.0f, 1.0f);
ssVba.Position<Float3>(1) = Float3(1.0f, 0.0f, 1.0f);
ssVba.Position<Float3>(2) = Float3(1.0f, 1.0f, 1.0f);
ssVba.Position<Float3>(3) = Float3(0.0f, 1.0f, 1.0f);
ssVba.Position<Float3>(4) = Float3(0.0f, 0.0f, 0.0f);
ssVba.Position<Float3>(5) = Float3(1.0f, 0.0f, 0.0f);
ssVba.Position<Float3>(6) = Float3(1.0f, 1.0f, 0.0f);
ssVba.Position<Float3>(7) = Float3(0.0f, 1.0f, 0.0f);
ssVba.Color<Float4>(0, 0) = ssColor;
ssVba.Color<Float4>(0, 1) = ssColor;
ssVba.Color<Float4>(0, 2) = ssColor;
ssVba.Color<Float4>(0, 3) = ssColor;

IndexBuffer* ssIBuffer = new0 IndexBuffer(12, sizeof(int));
int* indices = (int*)ssIBuffer->GetData();
indices[0] = 0; indices[1] = 1; indices[2] = 2;
indices[3] = 0; indices[4] = 2; indices[5] = 3;
indices[6] = 7; indices[7] = 4; indices[8] = 3;
indices[9] = 0; indices[10] = 4; indices[11] = 3;

TriMeshPtr mRectangle = new0 TriMesh(ssVFormat, ssVBuffer, ssIBuffer);
mRectangle->Update();

// Create a vertex color effect for the screen rectangle.
VertexColor4Effect* ssEffect = new0 VertexColor4Effect();
mRectangle->SetEffectInstance(ssEffect->CreateInstance());

return mRectangle;

How do I set what side is the visible face? Am I using the right terminology? I'm sure this engine can set it—I just don't know how.


texts:
Description:

Actor{
    int x,y,width,height;
    float speed, angle;
}

actor is an object that move around the map
every frame, actor change position(x,y) according to it’s speed & angle

Problem:

If: Next frame actor A will collide with actor B
Then: A should turn to what angle to evade B?


texts: Difference between column- and row vector matrix multiplication (vector transform)

texts:
Let's say we have a 4-by-4 matrix \$A\$ which represents some transformation.
We can use this matrix to transform a vector in two ways.

\$Ax\$ by assuming \$x\$ is a 4-by-1 column vector.
\$xA\$ by assuming \$x\$ is a 1-by-4 row vector.

Up until yesterday, I have not seen this \$xA\$ variant and I thought it was unnecessary. Then I came across this DirectX code from Microsoft.
This function takes just the projection matrix, computes the inverse projection matrix and then does this \$xA\$ variant (not \$Ax\$) to transform (or unproject) a bunch of coordinates.
At first, I wasn't looking and did \$Ax\$ which came out nonsensical and now I'm trying to understand why.
I've noticed that \$Ax = xA^T\$ but when I look at the way the matrix multiplication is carried out. The components that make up the result are very different depending on whether I use \$Ax\$ or \$xA\$ (as it should be, matrix multiplication is not commutative).
The analytic solution for \$Ax\$ (3-by-3 matrix and row vector)
$$
\begin{pmatrix}
x \\ y \\ z
\end{pmatrix}
\cdot
\begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i
\end{bmatrix}
=
\begin{pmatrix}
ax + dy + gz \\
bx + ey + hz \\
cx + fy + iz
\end{pmatrix}
$$
The analytic solution for \$xA\$ (3-by-3 matrix and column vector)
$$
\begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i
\end{bmatrix}
\cdot
\begin{pmatrix}
x \\ y \\ z
\end{pmatrix}
=
\begin{pmatrix}
ax+by+cz \\
dx+ey+fz \\
gx+hy+iz
\end{pmatrix}
$$
I use Mathematica to test these things. On a hunch I tried the analyitic solution for \$xA\$ with the elements of \$A\$ transposed manually and of course, I get:
$$
\begin{bmatrix}
a & d & g \\
b & e & h \\
c & f & i
\end{bmatrix}
\cdot
\begin{pmatrix}
x \\ y \\ z
\end{pmatrix}
=
\begin{pmatrix}
ax+by+cz \\
dx+ey+fz \\
gx+hy+iz
\end{pmatrix}
$$
Which is equivalent to \$Ax\$ except we now have a column vector not a row vector. I'm assuming all of this is purely conventional (and depends on whether I'm assuming row- or column-major matrix layout). It looks like I might have answered the question my self but if I'm wrong about anything here please correct me.