# Question
Title: Print string letter by letter in UI Text
i'm trying to print a string letter by letter for UI Text of Unity. With each click of a button, the Stampa function, must print a letter. Up to this point everything is working perfectly. But if I try to print a newline "\n" the function ignores him and continues to print on the same line.
This is my code:

```
using UnityEngine;
using UnityEngine.UI;

public class Click : MonoBehaviour {

    public static Text txt;
    public static int indice = 0;
    public string asd = "String1 \nStriga2";

    void Awake() {
        txt = GameObject.Find("Cmd").GetComponentInChildren<Text>();
    }

    public void Clicked() {
        Stampa(asd ,indice);
        indice++;
    }

    void Stampa(string stringa, int i) {
        txt.text += stringa[i];
    }

}

```

That produces this result(unwanted):

I also tried to print the entire string at the same time (not a letter at a time) as follows:

```
txt.text = "String1 \nStriga2";

```

That produces this result(wanted):
How can I get this second result by printing letter by letter?

# Answer
> 1 votes
It's reading one character at a time, so it's not properly escaping the new line. I would suggest looking for escape characters in your Stampa() function, and if it's an escape character, read the next character in at the same time. Something like:

```
void Stampa(string stringa, int i) {
    string r = stringa[i];
    if (r == '\\')
       r += stringa[i+1];
    txt.text += r;
}

```

Thought you'd likely need to return the index value to the calling function. You could return an int and maybe do something like this:

```
public void Clicked() {
        int val = Stampa(asd, indice);
        indice += val;
    }

int Stampa(string stringa, int i) {
        int ret = 1;
        string s = stringa[i];
        if (s == '\\')
        {
           s += stringa[i+1];
           ret++;
        }
        txt.text += s;

        return ret;
    }

```

---
Tags: unity, c#, text, ui-design
---


title: Core code obfuscation and scripting

text:
# Question
Title: Core code obfuscation and scripting
I am currently developing a 2D multiplayer game in Java and I would like to use Lua to define clientsided visual animations. Although this sounds like a reasonable idea to keep the core Java code to a minimum, these scripts would be depending on the core code and would therefore break if the core code is obfuscated (think of naming of classes and fields, imports).

What options do I have? Is there a way around this? If I was the head of a million dollar game development company I could just leave the source wide open without any obfuscation whatsoever but unfortunately I am not. Anyone could just reverse engineer the compiled code, modify it, alter resources and claim it as their own. I am aware that obfuscation does not completely stop that, but it does require someone to put a whole lot more effort into it.

I am currently still in an experimental design phase so I do not have any code examples of what I'd like to protect.

# Answer
Don't obfuscate the names or interfaces required by the scripting system; that way the scripts still bind to the correct types and functions and whatever by name.

If you need the code for those methods to be obfuscated, have the implementations of the scripting functions themselves call other set of internal implementations which *can* be obfuscated.
> 2 votes

# Answer
You shouldn't waste any resources on obfuscating your code in the first place.

You work is protected by copyright. When anyone steals it, just call your lawyer and sue them. Changing it so much that it can no longer be traced back to your work would be more work than writing it from scratch in the first place, so nobody will do that.

On the other hand, when your soucecode is available, you open up your game to a modding community. Most games really benefit from modding, because modders add more content to your game for free and greatly enhance its long-term value.

When you are worried about cheating, then preventing it client-sided is futile anyway. A skilled hacker will always be able to reverse-engineer your game client. Having the sourcecode makes it easier for them, but it's not strictly necessary. Games written in compiled programming languages do not thwart the hackers either. A far better way to prevent cheating is by designing your network protocol with an authoritative server. This means any game mechanics which could be interesting for a cheater to manipulate are calculated on the server where it is out of reach of the hackers.
> 1 votes

# Answer
Whenever I read a question like this I really love to cite some basic rule I've read on the internet years ago (and it's still true):

> The client is in the hands of the enemy.

So whatever you do: If you think players might change it to cheat, don't provide that part of the code in the first place. While code obfuscation might be a tiny step towards this goal, it's usually futile, because there are even modern tools to deobfuscate code. Picking a different language that is harder to disassemble (like C++ over Java) might be a even bigger (and significantly more effective) step, although not perfect either.

**There's no perfect protection,** no matter what you do, except taking the code to be protected from the client and moving it server side (assuming that's possible). Otherwise there will always be people putting hours or even days of work into getting some cheats to work, even if it's just some pointless tapping marathon on mobile with a high-score table.

So, if possible, change your game design to respect the quote mentioned above:

* **Never ever allow any clients to dictate something on the server.**

If the client claims to shoot, let the server check, whether that player is actually allowed to shoot. If so, let him do it. Same goes for movement or pretty much every other "move". To reduce lag, clients might show feedback instantly (shooting animation, movement, etc.) but the server must always have absolute power and be able to correct any abnormalities (often seen and named as "rubberbanding" in online games).
* **If you don't have a strict server/client separation (like peer-to-peer matchmaking), either elect one host temporary or let peers vote over important events** (might be complicated).

For example, when voting for the next map, all peers count the votes and the majority will determine the winning vote. If 4 out of 5 peers say "map 1" is next, but one peer claims "map 2", you know who's manipulated or simply lieing. In a similar way you could ensure checksums of scripts and similar, but this may be open for manipulation once again.
* **Never tell clients/peers things they don't have to know.** Imagine a stealth game. If one player has a modified client, he might be able to see all enemies all the time, ignoring their "stealth" flag. However, a cheat like this won't work, if his client won't get any information about players unless they're actually visible.
> 1 votes

---
Tags: scripting, security, anti-cheat
---


title: How to pool child classes in LibGDX?

text:
# Question
Title: How to pool child classes in LibGDX?
I have a super class named `Monster` which implements `Poolable`. Then I got child classes which extends from the `Monster` class, but I can not figure out how I will use pool and maintain only one set of pool array.

Here is my current pool setup:

```
public class GameWorld {

    // Map
    private TmxMapLoader mapLoader;
    private TiledMap map;

    // Creatures
    private Player player;
    private final Array<Monster> activeMonsters = new Array<Monster>();
    private final Pool<Monster> monsterPool = new Pool<Monster>() {
        @Override
        protected Monster newObject() {
            return new Monster();
        }
    };

    public GameWorld(String path) {
        mapLoader = new TmxMapLoader();
        map = mapLoader.load(path);
        player = new Player();
        player.init("Player", this, new Vector2(5, 5));

        Monster firefox = Pools.obtain(Firefox.class);
        for (int i = 0; i <= 10; i++) {
            firefox.init("Firefox", this, new Vector2(8, 8));
            activeMonsters.add(firefox);
        }
    }

    public Player getPlayer() {
        return this.player;
    }

    public TiledMap getMap() {
        return map;
    }

    public Array<Monster> getMonsters() {
        Monster monster;
        int len = activeMonsters.size;
        for (int i = len; --i >= 0;) {
            monster = activeMonsters.get(i);
            if (monster.isVisible == false) {
                activeMonsters.removeIndex(i);
                monsterPool.free(monster);
            }
        }

        return this.activeMonsters;
    }
}

```

# Answer
The short answer is that you can't return different subclasses from a Pool. Even if you used a static variable to pass parameters to `newObject()`, `newObject()` is only called when all of the pooled objects are already being used; meaning that you would never know which subclass you are getting when you obtained a pooled object.

Before continuing down this path, you may want to ask yourself, are you creating and destroying Monsters frequently enough to require pooling?

The next logical option is to create a `MonsterFactory` which contains a `Pool` for each monster type. You can create an `enum` for each monster type and pass it to a "`public Monster createMonster(MonsterType type)`" function. That way, you still have a uniform interface to generate your monsters and only the `MonsterFactory`has to keep track of the pools. Here's an example.

```
public class MonsterFactory{
    public Enum MonsterType{
      BIRD,
      RAT
    };

    private final Pool<Bird> birdPool = new Pool<Bird>() {
        @Override
        protected Bird newObject() {
            return new Bird();
        }
    };
    private final Pool<Rat> ratPool = new Pool<Rat>() {
        @Override
        protected Rat newObject() {
            return new Rat();
        }
    };

    public Monster createMonster(MonsterType monsterType){
       switch(monsterType){
         case BIRD:
            return birdPool.obtain();
         case RAT:
            return ratPool.obtain();
       }
    }

    //You must call destroyMonster whenever you are done with the monster or the pool will leak.
    public void destroyMonster(Monster monster){
       if(monster instanceof Bird){
         birdPool.free((Bird)monster);
       }
       else if(monster instanceof Rat){
         ratPool.free((Rat)monster);
       }
    }
}

```

However, if you are totally opposed to creating a Pool for each subclass, use Composition Over Inheritance. Using this method, you wouldn't use sub-classes for monsters, but you would instead plug-in their behaviors.

For example, if you want your monsters to move in various ways, say ZigZag and Straight Lines, you could have an `IMovement` interface member inside of your monster class that defines how the monster moves. You would then create them this way

```
IMovement zigZagMovement = new ZigZagMovement();
IMovement straightLineMovement = new StraightLineMovement();

public Monster createMonster(MonsterType monsterType){
    Monster newMonster = monsterPool.obtain();
    if(monsterType == MonsterType.Alligator){
       newMonster.movement = zigZagMovement ;
    }
    else if(monsterType == MonsterType.Zombie){
       newMonster.movement = straightLineMovement ;
    }
    return newMonster;
}

```

Then in your `Monster` class

```
public class Monster extends Actor
{
    public IMovement movement;

    public void act(float deltaTime){
       movement.move(deltaTime,this); //Updates the monster's movement
    }
}

```
> 2 votes

# Answer
If I'm not mistaken, you want to create a pool of different monster without creating many pools? If yes, just create a `MonsterPool` that extends `Monster`

```
public class MonsterPool<T extends Monster>  extends Pool<T>{

}

public MonsterFactory<T extends Monster> {

     Array<T> activeMonster = new Array<T>();
     MonsterPool<T> monsterPool = new MonsterPool< T>();

     public T obtainMonster () {
          return monsterPool .obtain();
     }

}

```

and use it like this.

```
new MonsterFactory<Slime.class>().obtain();
new MonsterFactory<Dinosaur.class>().obtain();

```
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: How can I get all components of a type from a List with mixed components?
I have a list of `GameObjects`. Half of these `GameObjects` have `Component1`, and the other half have `Component2`. I want to get all of `Component1` from the list.

So an example of my list:

```
var list = new List<GameObject>();
for (int i = 0; i < 10; i++)
{
    list.Add(new GameObject());
}
foreach(var go in list)
{
    if(UnityEngine.Random.Range(0.0f, 1.0f) < 0.5f)
    {
        go.AddComponent<Component1>();
    }
    else
    {
        go.AddComponent<Component2>();
    }
}

```

I can get all of `Component2` by using LINQ as such:

```
var components1 = list.Where(g => g.GetComponent<Component1>()).Select(r => r.GetComponent<Component1>()).ToList();

```

But that is very dirty and seems repetitive. Is there a better way to do this?

# Answer
LINQ is probably the best way to go, but switch your Select and Where so you don't have to call `GetComponent` twice

```
var components1 = list.Select(r => r.GetComponent<Component1>()).Where(g => g!= null).ToList();

```
> 1 votes

---
Tags: unity, c#, software-engineering
---


# Question
Title: Skeletal animation with multiple animations running at the same time
I've spent a long time attempting to figure out how complex animations are done and wrote quite a few different skeletonish frameworks myself, but they've never really came out good enough to be properly used. So maybe someone here knows how complex things that can have lots of different animations are animated. I know that you can combine different animations to create one larger thing, but that takes A LOT of time and can't be organised properly, or even designed properly if you are attempting to design complex characters.

So I'm wondering whether anyone knows about known techniques for this, I'm willing to write my own implementation of it (Using a quite unpopular language, usually can't find libraries or anything for it). Or a software that you can write an implementation of your own in your own language.

TL;DR: Looking for software / animation theory that can handle applying multiple different animations of the same character.

Spine2D and spriter aren't what I'm looking for.

# Answer
Look into a package like maya. It is much easier to learn how animation works that way than trying to do it programatically and looking at other people's code. On the game engine side you generally use interpolators to combine multiple animations together, but if you don't pick up the basics animation is very confusing. Even many supposed pro game programmers say some pretty dumb things on the topic because they don't really know much about animations per se, just how various game engines use them.

To get reasonable performance you are probably going to have to use C++ as well.
> -1 votes

---
Tags: 2d, animation, skeletal-animation
---


title: Earth-like acceleration seems slow

text:
# Question
Title: Earth-like acceleration seems slow
I wanted to make a kind of "fill the box" style game where you hold down to increase size of a ball that falls when you let go, end goal being covering a percentage of the screen.

Anyway, I wanted to attempt to make the engine myself for learning purposes (fiddle). However, using 9.8 as a global acceleration makes it feel like really low gravity.

So far, all of my movement is done via the function below. I feel like I'm missing something obvious, but just can't figure out why it seems more like moon gravity than Earth.

```
dt = new Date().getTime();
dt = (dt - lastFrame) / 1000;
for (var c in circles) {
  circles[c].v.y += acceleration * dt;

  if (circles[c].x + circles[c].v.x * dt > canvs.width || circles[c].x + circles[c].v.x * dt < 0) {
    circles[c].v.x *= -1;
  }
  if (circles[c].y + circles[c].v.y * dt > canvs.height || circles[c].y + circles[c].v.y * dt < 0) {
    circles[c].v.y *= -1;
  }

  circles[c].x += circles[c].v.x * dt;
  circles[c].y += circles[c].v.y * dt;
}
lastFrame = new Date().getTime();

```

# Answer
As noted in a comment above, this is about units. If you use the value 9.81 as pixels/s² it's like watching something fall hundreds of meter when the ball shall cross the entire screen. It takes 9 seconds for something to fall 400 meters with v0 = 0, neglecting air resistance. It should be clear why this appears moon-like. **It's all a matter of scale.**

To solve this for your game you have to define a coordinate system yourself (How many pixels match 1 meter?) or just tweak your value up a bit. This gets more complicated if you want to allow the player to zoom in or out, as the coordinate system changes when doing this.

Sidenote: If you use a graphics API (Direct3D or OpenGL) this adjustment is more or less automatically done for you if your Matrix library supports direct creation of world-, view-, and projection-matrices.
> 4 votes

---
Tags: 2d, mathematics, game-mechanics
---


# Question
Title: smooth loading of the heavy scene in unity3d
I have a very very **big/huge scene** to load, I can't load it at once. So what I know I have applied but it still loading takes some time I want to make it smooth. How it possible?

What i have tried so far is **I divided the scene into multiple scenes and loading it into async manner as my character controller move.** I am moving my character controller and accordingly loading (its near)scenes by matching its position.

How do i load smoothly a big scene? what will be the strategy? Is this right strategy which I am doing or there any else solution.

# Answer
> 1 votes
You can try Application.LoadLevelAdditive

> Unlike LoadLevel, LoadLevelAdditive does not destroy objects in the current level. Objects from the new level are added to the current scene. This is useful for creating continuous virtual worlds, where more content is loaded in as you walk through the environment.

# Answer
> 0 votes
Like dnk drone.vs.drones said, LoadLevelAdditive is likely going to help with how you've got it set up currently.

You might want to look into something more like a chunk-based loading system, however. Only rendering near chunks and using appropriate LOD's seems to be more standard in the industry. I've got a feeling it's better for your performance as well, but I'm not too sure on the specifics of how Unity handles LoadLevelAdditive.

---
Tags: unity, c#
---


# Question
Title: Is this process for generating an OpenGL perspective projection correct?
I have been programming OpenGL for a while now and I have successfully created a perspective camera, however, I can't help but shake the feeling that I am doing it wrong. The code I am using is below, is there something wrong with how I am constructing the perspective projection?

```
int MainWindow_SDL::execute(QCoreApplication &app)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    glewInit();

    // ...

    glLoadIdentity();
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_MODELVIEW);
    glDisable(GL_LIGHTING);
    gluPerspective(50, 1.33, 1, 1000);
    gluLookAt(3, m_xAxisLocation, 4, 0, 0, 0, 0, 1, 0);
    glewExperimental = GL_TRUE;

    // ...

    GameStart();
    app.exit();

    return 0;
}

```

I also set it up in the game loop:

```
void MainWindow_SDL::GameLoop()
{
    OpenGLRenderer t_renderer;
    t_renderer.PreGameRender();

    while (m_state == GameState::RUNNING)
    {
        glPushMatrix();
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glLoadIdentity();
        processInput();
        glMatrixMode(GL_MODELVIEW);
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_DEPTH_TEST);
        gluPerspective(50, 1.33, 1, 1000);
        gluLookAt(m_xAxisLocation, m_yAxisLocation, m_zAxisLocation,
                  0, 0, 0, 0, 1, 0);

        t_renderer.DuringGameRender();

        SDL_GL_SwapWindow(m_window);
        glPopMatrix();
    }

    t_renderer.PostGameRender();

    GameEnd();
}

```

# Answer
> 2 votes
```
glMatrixMode(GL_MODELVIEW);
glDisable(GL_LIGHTING);
gluPerspective(50, 1.33, 1, 1000);
gluLookAt(3, m_xAxisLocation, 4, 0, 0, 0, 0, 1, 0);

```

This kind of thing is generally wrong. What've you've done here is set the active matrix stack to the model-view stack; this is responsible for generating the matrix transform that will bring your rendered geometry into view space (for fixed-function lighting).

However, while this stack is active you're calling `gluPerspective`, which builds a perspective projection matrix and multiplies it onto the stack. Then you build a look-at (view) transform using `glLookAt`.

Generally you want to put the projection matrix into the dedicated projection matrix stack by doing things this way:

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(50, 1.33, 1, 1000);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(m_xAxisLocation, m_yAxisLocation, m_zAxisLocation, 0, 0, 0, 0, 1, 0);

```

---
Tags: opengl, c++, 3d
---


# Question
Title: Unity Rotation - Object is rotating on Z, but should be rotating on X
I've been working on a project where I have a cube. When swiped left, the cube will rotate 90 degrees the left, and then when swiped right, the cube will rotate 90 degrees to the right. I have this area working fine.

However, when i go to swipe up and down (To rotate the cube 90 forwards) it becomes slightly unstuck. If the rotation of the object is (0, 0, 0), it works fine. But if I, for example, rotate once to the left and then tried rotate fowards, the cube will correctly rotate left, but then the forward rotation will rotate on the Z axis and just spin the cube (So the face looks like its moving in right in a clockwise direction).

Here is the code:

```
public Transform rotateAround;
public float rotateSpeed;

bool isRotating;
Touch touchOn;
Touch touchEnd;

float changeX, changeY;

// Update is called once per frame
void Update()
{
    if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        touchOn = Input.GetTouch(0);
    }

    if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        touchEnd = Input.GetTouch(0);
        var difference = touchOn.deltaPosition - touchEnd.deltaPosition;

        changeX = (touchOn.position.x - touchEnd.position.x);
        changeY = (touchOn.position.y - touchEnd.position.y);

        Debug.Log("Changes: x: " + changeX + " y: " + changeY);

        if (changeX > 25f)
        {
            StartCoroutine(Rotate(transform, rotateAround, -Vector3.up, 90, rotateSpeed));
        }
        else if (changeX < -25f)
        {
            StartCoroutine(Rotate(transform, rotateAround, Vector3.up, 90, rotateSpeed));
        }

        if (changeY > 25f)
        {
            StartCoroutine(Rotate(transform, rotateAround, Vector3.left, 90, rotateSpeed));
        }
        else if (changeY < -25)
        {
            StartCoroutine(Rotate(transform, rotateAround, -Vector3.left, 90, rotateSpeed));
        }
    }
}

public IEnumerator Rotate(Transform thisTransform, Transform otherTransform, Vector3 rotateAxis, float degrees, float totalTime)
{
    if (!isRotating)
    {
        isRotating = true;

        Quaternion startRotation = thisTransform.localRotation;
        Vector3 startPosition = thisTransform.position;

        transform.RotateAround(otherTransform.position, rotateAxis, degrees);

        Quaternion endRotation = thisTransform.rotation;
        Vector3 endPosition = thisTransform.position;

        thisTransform.rotation = startRotation;
        thisTransform.position = startPosition;

        float rate = degrees / totalTime;

        for (float i = 0.0f; i < degrees; i += Time.deltaTime * rate)
        {
            yield return null;
            thisTransform.RotateAround(otherTransform.position, rotateAxis, Time.deltaTime * rate);
        }

        thisTransform.rotation = endRotation;
        thisTransform.position = endPosition;
        isRotating = false;
    }
}

```

Both the camera and the cube start with rotations of 0, 0, 0. The script is placed on the camera, with the rotateAround transform object been set as a cube.

Any help would be appreciated!

# Answer
> 1 votes
You describe your problem rotating a cube, but it seems to me that you are having the camera orbit around the cube. However, the vectors you are using for the axes of rotation are in world space, and do not rotate with the camera. After you have rotated left by 90 degrees, Vector3.left is now facing directly into the camera. As such, your next swipe for a "forward" rotation just causes the camera to spin in place.

If you want a fixed background, where the cube is the only thing that moves, you will have to rework the code to rotate the cube with respect to a fixed camera.

If you want the camera to move around the cube as well as the background and everything else, then you should use axes of rotation that are relative to the camera. Instead of Vector3.forward, Vector3.left, and Vector3.up, you should use transform.forward, transform.right, and transform.up (with appropriate signs for the two directions of rotation).

---
Tags: unity, c#, rotation
---


# Question
Title: Is it definitely impossible for a user to alter data stored server-side in an online game?
Does storing game data server-side definitely prevent cheating related to that data (by altering it, et cetera)?

# Answer
If you're careful enough, your typical users will not be able to change this data on your own servers (see Josh's answer).

However.

It does not mean that they won't be able to cheat *related to that data*.

If your game transfers this data to your users every time they need it, they still could discard it, replace it by their own, perform game simulation based on their own parameters, and send the 'new state' of the simulation to your server. If you don't counter-validate their actions with your own set of server parameters and data, and just assume that what you sent 'must be valid' (because I sent them the correct parameters (right?)), they'll be able to cheat.

> Is it definitely impossible for a user to alter data stored server-side in an online game?

Yes, it's possible to achieve this.

> Does storing game data server-side definitely prevent cheating related to that data (by altering it, et cetera)?

No, only storing game data server-side does not definitely prevents cheating related to that data.
> 1 votes

# Answer
No.

It makes it so difficult to alter the relevant data for malicious (cheating/hacking) purposes that it is *effectively impossible* for most *casual players* who would want to cheat to do so or to obtain cheat software to help them do so.

However, it's not *technically* impossible. Just like hackers can breach the security of social networking websites, bank websites and the US Office of Personnel Management, hackers could breach the security of any data centers or server clusters used by any online game out there.

Anti-cheat paradigms in games are primarily about raising the bar so high that it's improbable. Storing data server-side does that (for that data, at least; see Alexandre's answer). It makes the task so difficult that the payoff (infinite HP!) isn't worth the effort. At that point, if hackers were able to penetrate a game's server-side security, they'd probably be far more interested in obtaining any payment or personal information from the user database; that's far more likely to be profitable than giving their characters infinite gold is.
> 1 votes

---
Tags: networking, security, anti-cheat
---


# Question
Title: best way to handle when a game is active?
I'm facing a problem with a game I'm making on C#. I have a status for the game to decide if it's active or not.

However, there are many moments when it must be paused

* don't have focus
* a menu is opened
* moving the window
* not visible

It's starting to be lots of checks to lots of place to have those conditions working.

I'm trying to do like FCEUX which is genial.

Right now I need the following event from the form:

OnDeactivate, OnActivated. Then, if clicking on a menu, the form is activated but needs to be stop. I then need to also include events for when a menu is clicked.

Then someone can move the application with the mouse, this also requires another event... and on and on...

# Answer
You just need to set some boolean value indicating you should pause your game when you detect any of the conditions you listed. It sounds like you're using Windows Forms; this means you can detect all of your conditions as follows:

* "don't have focus" Listen for the activated and deactivated events. A form must be activated to have input focus.
* "a menu is opened" This is tricky, as games generally don't *have* OS-style menus, and those that do don't generally need to pause when they open. That said, you can probably hook `MenuStart` to detect this and `MenuComplete` to resume the game.
* "moving the window" There are events for starting and stopping a resize operation; these fire when moving the form as well and so should cover all those cases.
* "not visible" Look at `VisibleChanged`.

Some classes of low-level events aren't exposed to you via the Windows Forms API. In those cases you'll need to manual handle them in a `WndProc`; that means subclassing the `Form` class and overriding the `WndProc` method correctly (make sure to call the base class version if you don't handle the message yourself). That will let you detect clicks in the title bar and other non-client areas of the form (handle `WM_NCLBUTTONDOWN` and the corresponding button-up message).

I'm not sure if the `NC` messages will fire when you click the system menu; in general it doesn't seem like you can get a message for that menu opening (probably because "you don't own it"). Your best bet may be to disable that menu in your window style.

It's true you'll be adding a fair number of hooks for all the events and scenarios you want covered to pause your game, but there isn't much you can do about that (other than to decide you don't care about pausing for some conditions). As long as your factoring out the actual code for handling the pause, and only setting some kind of `shouldPause` variable to true or false in the bodies of all these event handlers, it shouldn't be *that* big of a maintenance burden.
> 3 votes

---
Tags: c#
---


# Question
Title: Tile Based Collision With Moving Platforms
I am developing a platformer using pure HTML/Javascript. After remaking my collision detection system with help from HTML5 platformer collision detection problem, I realized my moving platform detection would not work because my moving platforms (only a vertically moving wall to block the player, at the moment) are not rendered using the tilemap. Currently, I am manually pushing it to the array of obstacles in the level. Here is my collision detection code:

```
function collisionDetection() {
    player.onLadder = false;
    var bottomY = player.y + player.height;

    var bottomCol = collisionCheck(player.x + (player.width / 4), bottomY) || collisionCheck(player.x + (player.width / 2), bottomY)
        || collisionCheck(player.x + ((3 * player.width) / 4), bottomY);
    var topCol = collisionCheck(player.x + (player.width / 4), player.y) || collisionCheck(player.x + (player.width / 2), player.y);
    var leftCol = collisionCheck(player.x, player.y) || collisionCheck(player.x, player.y + (player.height / 2));
    var rightCol = collisionCheck(player.x + player.width, player.y) || collisionCheck(player.x + player.width, player.y + (player.height / 2));

    if (bottomCol) {
        player.y -= (bottomY % 32);
        player.onGround = true;
        player.jumping = false;
    }

    if (topCol) {
        player.velY *= -1;
    }

    if (leftCol && !topCol) {
        player.x -= ((player.x + player.width) % 32) - player.width;
        player.jumping = false;
    }

    if (rightCol && !topCol) {
        player.x -= ((player.x + player.width) % 32);
        player.jumping = false;
    }

    if (!bottomCol && !leftCol && !rightCol) {
        player.jumping = true;
        player.onGround = false;
    }
}

function collisionCheck(x, y) {
    var tile = maps[level][y >> 5][x >> 5];
    //collectibles like coins
    if (tile == 14 || tile == 15 || tile == 16) {
        collectiblesCheck(x, y, tile);
        return false;
    //0 is an empty space in the map
    } else if (tile != 0) {
        return true;
    }
}

```

Essentially, the code finds the closest tile to the player and does necessary adjustments based on where the collision occurs. Since the moving wall is not a tile, I am unsure of the best way to deal with collision detection. I could use my old collision detection method, which traversed through the obstacle array instead of the map tiles, but I feel that that would be too inefficient.

If any of the code needs explaining, please feel free to ask. Thank you.

# Answer
> 1 votes
As long as you have the position of the moving wall and the size of it, as well as the position of the player and the player size, it's easily doable without using a tile map :)

I posted three guides based on shape collision, so check them out:

---

For testing if a point is inside a polygon, use the code I posted below. I wrote this in C# based off of the question asked here (the second most up-voted answer), so you should definitely take a look on how it works and how to use it.

(One of my favorite methods \<3 )

```
public static bool PolyCollide(int nvert, float[] vertx, float[] verty, float testx, float testy)
    {
        int i, j;
        var result = false;
        for (i = 0, j = nvert - 1; i < nvert; j = i++)
            if ((verty[i] > testy != verty[j] > testy) &&
                (testx < (vertx[j] - vertx[i])*(testy - verty[i])/(verty[j] - verty[i]) + vertx[i]))
                result = !result;
        return result;
    }

```

---

For testing if a rectangle hit another rectangle, take a look at the answer I wrote here. It provides a good explanation and direction on what you need to do. This is probably the logic you want to implement in your game, using the tiles as rectangles and such

---

For collision detection concerning polygon to polygon (basically uses the Separate Axis Theorem), take a look at this source, though I doubt you need it.

I hope this helps, and good luck on your game!

---
Tags: collision-detection, javascript, moving-platforms
---


# Question
Title: C++ MMO: Best approach to store creatures in a multi-level world map for the purpose to find spectators
I'm developing a game which is a multi-level game, my game can have a maximum of 15 floors, and a fixed amount of tiles width/height.

Each tile in the map can have a creature. All fine until here; I need to find spectators within a range / radius of the map, and sometimes within specified floor ranges, this can happen multiple times per second (players interacting with the world)

Currently this is how I search for lets say all spectators in all floors:

```
for (int floor = 0; floor != 15; floor++)
{
    for (int x = posx - range; x != posx + range; x++)
    {
        for (int y = posy - range; y != posy + range; y++)
        {
            Tile* ....
            Spectators.Add(Tile->GetCreature());
        }
    }
}

```

As you can tell, this isn't the best approach, I've thought about using a hash / chain of creatures on which each hash entry points to a X-Y coordinate in the world map, this would take a lot of trouble to worry about floors, and it's also more performance-friendly.

How can I achieve this?

# Answer
"Spectators" is just the list of nearby enemies, right?

Anyways, I can think of 2 good ways to do this: Look at nearby tiles to see if they have monsters, or look at monsters to see if they're on a nearby tile.

If you are going to choose the route of looking at tiles for monsters (better for densely populated levels), your existing code can be made cleaner:

* Make sure to specify the floor on which you are looking. I doubt that there's generally a need to loop through all 15 levels.
* If levels are sufficiently large that the radius/range is a small percentage of the total space, consider only checking tiles within a square around the central point: from x / y minus the range to x / y plus the range.

In this case, I'd suggest continuing to store monsters as you seem to be doing, assigning each tile a slot for a monster.

If you want to check monsters to see if they're nearby (better for a sparsely populated map), store separate lists (in whatever data structure) of monsters per-level. Loop through the list and test each monster against whether or not it is in range of the target. This way, the X/Y coordinates would be stored more directly as a property of the monster.

If you want, you could combine both of these strategies for the final implementation. Divide the total floor space into a 2d array of smaller chunks, and store a list of monsters in each chunk. For checking which monsters are in range of the given point, just look at the monsters in the nearby chunks. That way you can quickly eliminate looking at monsters or tiles which are obviously in chunks too far away, and then

Also: Your code is going to try to loop through 16 floors. It'll stop on floor=16, but floor=0 to floor=15 is 16 times looping.
> 1 votes

# Answer
Let the info about its position in the world be part of the monster class. Then you are only searching all the monster, when deciding if they are in the range, not all the tiles.

Also take in consideration, that if your map has floors, you need 3D coords: x,y,z...
> 1 votes

---
Tags: c++, mmo, logic
---


# Question
Title: Need Help With My Script And Animator. I am encountering a few bugs with it
Okay so I have created a player archer character which when he using the arrow keys, faces those directions and upon hitting space when in that direction, the bow attack animation is played.

The code works fine but there are some nerve-wrecking problems:

when I unpress an arrow key, the character always returns to his default direction and when I press space when no arrow key is pressed, the right bow attack animation is played and also when i press the up arrow key and the space bar, the up bow attack animation does not play and instead again,the right bow attack animation is played.

I have looked at everything again and again but I can't seem to find anything wrong. The animation's assigned are okay and the code is okay too. Don't know what's wrong. I have been stuck at this problem all day.

I have attached some screenshots so you can see how I have achieved this:

my animator here

my blend tree in the idle state is here and so far, this is my script:

```
public class PlayerDirectionAndShooting : MonoBehaviour
{
     Rigidbody2D rbody;
     Animator anim;

     void Start ()
     {
         rbody = GetComponent<Rigidbody2D>();
         anim = GetComponent<Animator>();
     }

     void Update ()
     {
         Vector2 direction_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
         anim.SetFloat("input_x", direction_vector.x);
         anim.SetFloat("input_y", direction_vector.y);

         if (Input.GetKeyDown("space"))
         {
            if (anim.GetFloat("input_x") <= -1)
            {
                anim.SetBool("is_shooting_left", true);
            }
         }
        else
        {
            anim.SetBool("is_shooting_left", false);
        }

        if (Input.GetKeyDown("space"))
        {
            if (anim.GetFloat("input_y") <= -1)
            {
                anim.SetBool("is_shooting_down", true);
            }
        }
        else
        {
          anim.SetBool("is_shooting_down", false);
        }

        if (Input.GetKeyDown("space"))
        {
            if (anim.GetFloat("input_y") <= 1)
            {
               anim.SetBool("is_shooting_up", true);
            }
        }
        else
        {
            anim.SetBool("is_shooting_up", false);
        }

        if (Input.GetKeyDown("space"))
        {
            if (anim.GetFloat("input_x") <= 1)
            {
                anim.SetBool("is_shooting_right", true);
            }
        }
        else
        {
            anim.SetBool("is_shooting_right",false);
        }
    }
}

```

# Answer
I rearrange code here(for the jump and attack part):

```
         if (Input.GetKeyDown("space"))
         {
            if (anim.GetFloat("input_x") < 0)
             {
                 anim.SetBool("is_shooting_left", true);
                  anim.SetBool("is_shooting_right", false);
             }
              if (anim.getFloat("input_x") > 0)
             {
                  anim.SetBool("is_shooting_left", false);
                  anim.SetBool("is_shooting_right", true);
             }
             if (anim.GetFloat("input_y") < 0)
             {
                  anim.SetBool("is_shooting_down", true);
                  anim.SetBool("is_shooting_up", false);
             }
              if (anim.GetFloat("input_y") > 0)
              {
                  anim.SetBool("is_shooting_down", false);
                  anim.SetBool("is_shooting_up", true);
             }
         }

```

it should work.

* having multiple if (GetKeyDown("space")) is wrong.
* it's better to compare anim.GetFloat(input\_x"or y") with 0. not 1 and -1 ( i don't know why you did that)
> 0 votes

---
Tags: unity, c#
---


# Question
Title: create continuous snake like slither.io MonoGame c#
I need help creating a snake with continuous smooth motion like slither.Io up till now I just can't find any but the grid snake.

**EDIT:** Following a curve with the snake, Grow that snake.

# Answer
The thing is, in slither.io, the snake isn't following a spline at all. Each segment simply follows the previous segment.

So create a head and a bunch of segments. The head is just a special segment with your movement and other logic in it:

```
class SnakeHead:SnakeSegment
{
   List<SnakeSegment> Body = new List<SnakeSegment>(); //keep the bodyparts here so we can update them easily

   //do your steering logic etc here.
}
class SnakeSegment
{
   Vector2 Position;
   SnakeSegment Parent;
}

```

Then create the snake:

```
    SnakeHead Snake = new SnakeHead();
    SnakeHead.Position = new Vector2(100,100);

    SnakeSegment parentsegment = Snake;

    for (int i = 0; i < 10; i++) // 10 segements seems okay.
    {
        SnakeSegment bodypart = new SnakeSegment();
        SnakeSegment.Position = parentsegment.Position;
        SnakeSegment.Parent = parentsegment;

        Snake.Body.Add(bodypart); // add the bodypart to the list
        parentsegment = bodypart; // remember this one for the next bodypart.
    }

```

So each segment does something like the following:

```
void Update()
{
    if(Vector2.Distance(parent.Position,this.Position)>_minDistanceBetweenSegments)
    {
        Vector2 Orientation = (Parent.Position - this.Position).Normalize();
        this.Position += Orientation * _followSpeed;
    }
}

```

This checks if the head is further away from the previous segment than you want (`_minDistanceBetweenSegments`); if it is, move it into the direction of the previous segment. If the `_followSpeed` is equal to the movement speed of the head, the snake will trail instantly. Due to the `Orientation` the snake will flow nicely as in the Slither.io game.

So have the head loop through the bodysegments, and call update in those segments and you're set.

(code is untested; just for illustrating how the effect of a segmented trailing snake works)
> 1 votes

---
Tags: c#, game-design, monogame, game-mechanics
---


title: 3D Menu Attached to an Object?

text:
# Question
Title: 3D Menu Attached to an Object?
So I'm gathering information for my project, and one of the things I want to achieve is to create a very sophisticated crafting system and weapon modification but I want the weapon customization to look in a specific manner.

A very good reference would be Crysis weapon attachments system, where if you open it, your character tilts the weapon and there are few menus popping up, all attached to the weapon, so you can see the menus moving around as your weapon is moving (due to you breathing for example, or walking).

Here is a quick image reference:

So 1st thing comes to my mind is, how in the name of god should I approach this? Pardon if this is quite easy thing to do, I'm just completely new to Unity. (I have solid C++ background so programming isn't the obstacle)

Edit 1: To be precise, I'm wondering how to work out the positioning of the menus in relation to the weapon. So the menu is moving with the weapon and eventually even turn slightly to give that 3D'ish effect.

# Answer
To "attach" 2D menus to a 3D model like this, you can simply define the attachment points somehow in your model data. Often games will already have some kind of system for this, usually representing the attachment point as a 3D point on the model and a normal to indicate "forward" so that physical attachments (like a sniper scope) can be attached.

Unity doesn't appear to have this kind of thing as a first-class feature, but most people seem to implement it via empty named game objects attached to the model in question.

In this case you'd just need the position aspect of such an attachment point. In-game, look up that attachment point's world position and project it onto the screen using, for example, `Camera.WorldToScreenPoint`. That will give you a position to anchor your menu.

You may want to do something like test if the screen point is closer to the left or right edge of the screen, and use the projected anchor as the left or right origin of the menu (similar for the top and bottom) to prevent the menus from clipping offscreen, or something like that.
> 2 votes

---
Tags: unity, gui, menu
---


# Question
Title: Behaviours: Should I always return a reference to the behaviour on its methods?
I'm writing a small game to sharpen my programming skills, and I've chosen to use behaviors (that basically is a class that modifies its parent, to do things like movement, damage and stuff) to avoid duplicating code... maybe...

Whenever I need to modify the properties of a behavior, I need to get it from the "Actor", like this:

```
actor.getBehaviour(BehaviourType).method();

```

It's OK until I need to modify multiple properties, like following:

```
actor.getBehaviour(BehaviourType).method();
actor.getBehaviour(BehaviourType).setFoo(10);
actor.getBehaviour(BehaviourType).setBar("privet", "russian_hello");

```

Wouldn't that be more convenient if I just return a reference to the behavior on every method (every method needed)?:

```
actor.getBehaviour(BehaviourType).method().setFoo(10).setBar("privet", "russian_hello");

```

I apologize for any mistakes or broken logic (including broken grammar).

Thank you very much and have a nice day/afternoon/night/pokemongo/vim\>sublime but i use sublime anyways!

# Answer
> 1 votes
You do already return a reference to the behaviour with the getBehaviour method. You can store the reference in a variable and work with it. Personally, I wouldn't return the components from the other methods.

Something like the following if a local variable is enough:

```
YourBehaviour behaviour = actor.getBehaviour(BehaviourType);
behaviour.method();
behaviour.setFoo(10);
behaviour.setBar("privet", "russian_hello");

```

I'm not quite sure which language you're using, but it appears that you might benefit from some kind of generics (C#/Java) or templates (C++) to get a reference of the specific behaviour type and call the corresponding methods, so that you won't need to cast it explicitly all the time.

---
Tags: architecture, oop, behavior, haxe
---


title: 2D Animated Tile rendering

text:
# Question
Title: 2D Animated Tile rendering
The current game I've been working on needs to have animated tiles. I have a code for `Tile` and `TileMap` from my previous game that I recycled. However, it does not support tile animations.

The tile animations are independent from each other. Now, I have an `Animation` class for my sprites that looks like this (parts are ommited/abstracted):

```
function Animation(spriteatlas, frames, animationDelay){
    this.spriteAtlas = spriteatlas;
    this.frames = frames;                     // array of number of frames
    this.animationDelay = animationDelay;     // array of delays

    this.currentAnimationIndex = 0;

    this.currentFrame = 0;
    this.delayCounter = 0;
}

Animation.prototype.startAnimation = function(index){
    this.currentFrame = 0;
    this.delayCounter = this.animationDelay[index];
}

Animation.prototype.update = function(){
    this.delayCounter--;
    if(this.delayCounter === 0){
        this.currentFrame++;

        if(this.currentFrame == this.frames[i]){
            this.currentFrame = 0;
        }
    }
}

Animation.prototype.render = function(ctx){
    // Render the appropriate sprite
}

```

The actual `Animation` class has much more packed into it, since it is a generic animation.

I can just add an instance of the `Animation` in every tile, but I think it is inefficient and/or wasteful. Moreover, not all tiles are animated. One may argue that, yeah, it just costs a little memory since this is just a small game. But I do want to know and learn about more efficient ways so I can use them in my next bigger projects.

What are the techniques I can use?

# Answer
Probably the best lesson to learn from this "don't optimise too soon"; no matter how big your project gets, there is going to be a finite number of tiles being updated at any given time, so splitting hairs over implementation for efficiency reasons may be unnecessary.

To answer your question directly, I don't see a good reason not to treat all image as potential animations, where still images are 1-frame animations.
> 1 votes

# Answer
I'm doing effectively the same thing as you, although I think I have things organized a bit differently.

I have an object (struct actually) that stores information about each map tile, including if it has more than one frame and what the frame cycle time is. I then have a sprite-map object that contains all those tiles. I then update the sprite-map every tick and it updates any tiles that need to change frame.

This means all the animations update in sync, but each tile can animate at a different rate. The animation is cheap because it is just changing one number (active frame), and only on the tile type, not every instance. To make drawing cheaper you could use a Dirty-Rect system to only draw changed tiles. The sprite-map iterates through all its tiles and just skips any tile that doesn't contain the animated flag. Another optimization would be to store the list of animated tiles on load and only update those (although the ability to toggle animation could be neat).

You can read more about the system I'm working on in this blog post. I am using multiple layered views, and I latter refactored the code so each view gets its own independent copy of the tiles so the animations in different areas could be controlled separately.
> 0 votes

---
Tags: game-design, javascript, tilemap
---


# Question
Title: LibGdx - How can I correctly handle tile transitions / connected textures?
So I am making a tiled game and I need to connect textures correctly based on whats next to it.

With tiles that had connection really close to the edge of the tile I could just use the 4 bit meathod ie:

```
x 1 x
8 x 2
x 4 x

```

But for tiles with more detail I need to have corners too. I have seen people use the 8 bit meathod ie:

```
1   2  4
128 x  8
64  32 16

```

But really I can only see 48 different tile combos.

Is there a way I can separate corners and u d l r. Something like this:

```
x 1 x  8 x 1
8 x 2  x x x
x 4 x  4 x 2

```

Or is there a better way all together to do this.

This is what I have tried so far but this only uses 32/48 tiles and doesn't work for special corner cases.

```
public class RockTile extends Tile {

int y;

public RockTile(int id) {
    super(id);
    y = 7;
}

public TextureRegion getTexture(Level level, int xLoc, int yLoc){

    int u = (level.getTile(xLoc, yLoc + 1) != this) ? 1 : 0;
    int r = (level.getTile(xLoc + 1, yLoc) != this) ? 2 : 0;
    int d = (level.getTile(xLoc, yLoc - 1) != this) ? 4 : 0;
    int l = (level.getTile(xLoc - 1, yLoc) != this) ? 8 : 0;

    int bit = u + r + d + l;

    int ur = (level.getTile(xLoc + 1, yLoc + 1) != this) ? 1 : 0;
    int dr = (level.getTile(xLoc + 1, yLoc - 1) != this) ? 2 : 0;
    int dl = (level.getTile(xLoc - 1, yLoc - 1) != this) ? 4 : 0;
    int ul = (level.getTile(xLoc - 1, yLoc + 1) != this) ? 8 : 0;
    int corner = ul + ur + dl + dr;

    if (bit == 0) {
        if (corner != 0)
            return Game.splitTiles[y + 1][corner];
        else
            return Game.splitTiles[y][bit];

    } else {
        if (corner != 0)
            if (dl > 0 && l == 0 && d == 0)
                return Game.splitTiles[y + 2][bit];
            else
                return Game.splitTiles[y][bit];

        else
            return Game.splitTiles[y + 2][bit];
    }

}

}

```

If you need anything else let me know.

EDIT: Side question because I've seemed to have stumped you guys. If I decided to use the 8 bit method what would be the best and fastest way to make a lookup table for that.

# Answer
> 1 votes
For my system I use a spritesheet with 16 tile variations on it.

Upon creating a tile type I cut up the texture into regions specified in the constructor (which means my tiles can have varying resolutions).

That means you can provide it with an image like this http://www.promagra.de/Downloads/Platformer/Pl5t.png and the transitions will take care of themselves.

The is my simplified constructor for a tile type:

```
public class TileType {

    public final TextureRegion[] tileVariations;

    public TileType(String name, Texture texture, int regionSize){

        tileVariations = new TextureRegion[16];

        TextureRegion[][] tmp = TextureRegion.split(texture, regionSize, regionSize);

        tileVariations[0] = tmp[3][0];
        tileVariations[1] = tmp[2][0];
        tileVariations[2] = tmp[3][1];
        tileVariations[3] = tmp[2][1];
        tileVariations[4] = tmp[0][0];
        tileVariations[5] = tmp[1][0];
        tileVariations[6] = tmp[0][1];
        tileVariations[7] = tmp[1][1];
        tileVariations[8] = tmp[3][3];
        tileVariations[9] = tmp[2][3];
        tileVariations[10] = tmp[3][2];
        tileVariations[11] = tmp[2][2];
        tileVariations[12] = tmp[0][3];
        tileVariations[13] = tmp[1][3];
        tileVariations[14] = tmp[0][2];
        tileVariations[15] = tmp[1][2];

    }

}

```

Then every time an individual tile type has its tile type updated, I recalculate which sprite to use for the tile and its neighbours. The sprite to use is stored as an int / byte which is used to access a specific index of the tile variations array of the tile type.

Then you can simply render the correct texture of the tile type based on the display index of an individual tile.

Here is a simplified MapTile class:

```
public class MapTile {

    public final int xPos;
    public final int yPos;

    private final TileMap tileMap;

    private TileType tileType;
    private byte displayTile = 0;

    public MapTile(int x, int y, TileMap map){
        xPos = x;
        yPos = y;
        tileMap = map;
    }

    public void setTileType(TileType newType){
        tileType = newType;

        // Check the current tile
        checkNeighbours();

        MapTile neighbourTile;

        // Check the tile above
        neighbourTile = tileMap.getTile(xPos, yPos + 1);
        if(neighbourTile != null){
            neighbourTile.checkNeighbours();
        }
        // Check the tile below
        neighbourTile = tileMap.getTile(xPos, yPos - 1);
        if(neighbourTile != null){
            neighbourTile.checkNeighbours();
        }
        // Check the tile to the left
        neighbourTile = tileMap.getTile(xPos - 1, yPos);
        if(neighbourTile != null){
            neighbourTile.checkNeighbours();
        }
        // Check the tile to the right
        neighbourTile = tileMap.getTile(xPos + 1, yPos);
        if(neighbourTile != null){
            neighbourTile.checkNeighbours();
        }
    }

    public void checkNeighbours(){
        displayTile = 0;

        if(this.tileType == null){
            return;
        }

        // Check the tile above
        MapTile neighbourTile = tileMap.getTile(xPos, yPos + 1);
        if(neighbourTile != null){
            if(neighbourTile.tileType == tileType ){
                displayTile += 1;
            }
        }

        // Check the tile below
        neighbourTile = tileMap.getTile(xPos, yPos - 1);
        if(neighbourTile != null){
            if(neighbourTile.tileType == tileType ){
                displayTile += 4;
            }
        }

        // Check the tile to the left
        neighbourTile = tileMap.getTile(xPos + 1, yPos);
        if(neighbourTile != null){
            if(neighbourTile.tileType == tileType ){
                displayTile += 2;
            }
        }

        // Check the tile to the right
        neighbourTile = tileMap.getTile(xPos - 1, yPos);
        if(neighbourTile != null){
            if(neighbourTile.tileType == tileType ){
                displayTile += 8;
            }
        }
    }

    public void renderTile(SpriteBatch batch){
        if(tileType != null){
            batch.draw(
                    tileType.tileVariations[displayTile],
                    xPos * tileMap.tileSize,
                    yPos * tileMap.tileSize,
                    tileMap.tileSize,
                    tileMap.tileSize
            );
        }
    }
}

```

# Answer
> 0 votes
I am also picking tile variations based on a tile's eight neighbors. Encoding the neighborhood is fairly simple, but deciding what pattern each set of bits represents is kind of tricky. I currently just have collections of matching ints for each pattern, and I am checking each pattern type for containment.

I do have the impression that a Binary Trie could be used for fast pattern matching. For example if you changed the encoding order of the neighbors you could arrange for matching configurations to all have the same bit-prefix.

You can read more about what I came up with so far in this blog post.

---
Tags: java, libgdx, textures, tiles
---


# Question
Title: How can I prevent pinching and jagged edges when deforming joints in 3ds Max?
I've rigged and skinned a character, but no matter how or how much I blend the weights, it doesn't look good:

Why does the weight map look pixelated? I don't get it. I've never been able to get past this point when animating. I don't think it's a model resolution issue, since as you can see in the picture, the model is quite detailed.

How can I prevent the indicated problems?

Here are some reference images of my wireframe and weight maps:

EDIT

After recreating a model entirely to try and have another go at this, Ive found that my new model is repeating the previous outcome. Here are some images

enter image description here

# Answer
I'm not an artist and don't claim to be one; this answer is mainly based on hearsay and "articles I read on the internet."

Rigging and skinning works through math. There's no magic or physics involved, and an improperly-designed skin is going to cause you just as much trouble as an improperly-designed rig or an improper weighting. Based on your pictures I think your problem is that you mesh geometry isn't designed to handle deformation *at all*; you model the polygons around the joints exactly the same way as you model the polygons everywhere else, and at a very high resolution.

The problem is that "everywhere else" doesn't really deform under animation, but the joints do. If the topology of your mesh doesn't account for that, you get creases, jagged edges, and assorted unpleasant weirdness:

> To be able to sculpt good-looking muscle activity and corrective shapes, it’s important that your topology supports the correct creasing in required areas. Try not to use an extreme polygon density for the base model for the first skinning pass. Skinning a low-resolution character is much easier and takes a fraction of the time that is required to properly skin a subdivided character with more than 20,000 vertices.

Note, for example, the way this hand is built with geometry designed to support the deformation zones:

You probably need to modify or rebuild your hand model so that it contains that kind of supportive geometry. Remember that skinning only *moves* vertices, so you have to think about where the vertices will be before, after and during the application of a deformation. If they start to deform so they're inside the skin, you'll get weird visual discontinuities in the render. If they deform outside the skin, weird jagged edges, and so on.
> 2 votes

# Answer
There are two factors to consider when rigging a character to make sure that your get proper deformation. Firstly, topology. You have to make sure that the mesh has enough (and correct) topology in the area you are deforming to ensure that the geometry can stretch and move with the skeleton without looking terrible. In the case of your model shown, it looks almost like you arbitrarily added edge loops to the fingers as they're not spaced in any useful way. Its important to ensure that your edge loops go in where they'll benefit the deformation. Here's a great video showing how to do this properly: https://www.youtube.com/watch?v=J1mExXURsWk

The second thing to consider is the type of deformation you use which is rigid or blended deformation. It looks as if you're using rigid deformation on your rig, but it could also be that you simply haven't skinned the character to the bones properly. In 3ds max I ALWAYS recommend using either Biped or CAT when rigging a character as this will save you loads of time and comes with all of the IK/FK already setup. I then recommend using the Skin modifier over physique as it give you more control and makes it easier to rig your character. When using the Skin modifier the verts of your mesh will be color coded to visually represent the influence of a specific bone. Red means rigid (completely influenced by the bone) and blue means not at all influenced. Different shades of orange and yellow represent less influence which is what makes the rig blended - you can set verts to only move a little bit when you rotate the bone.

The Skin modifier does a pretty good job at assigning the skin weights to your skeleton but its sometimes necessary (almost always with hands) to tweak the default weights. When you have 3 edge loops around a knuckle the best strategy is to assign the top loop to the bone above it, the bottom loop to the bone behind and the middle loop to 0.5 on each. This will provide a smooth bend at the joint.
> 0 votes

---
Tags: 3dsmax, rigging
---


title: Making Cave system in Unity 5

text:
# Question
Title: Making Cave system in Unity 5
I know there are many threads about this but none of them seems to work for me and I spent like 2 days already on that problem. Things that I've checked:

It's like I see the way to accomplish that but can't really glue all the pieces together. It seems that to make a "hole" in terrain we have to:

1. Place an Cube/Plane with depth-mask shader onto our terrain (mountainside e.g)
2. Add collider to it and script with OnTriggerEnter/Exit where we have to ignore collision between player and terrain
3. Put an object with our cave system (made in 3ds/blender) inside our mount-shaped terrain and camouflage the edge of entrance with other objects e.g rocks so we wont see any artifacts.

I don't want to use voxel terrain, instead of depth-mask I could use transparent terrain texture paint option.

Do You know any working example for version 5.3.5 or could You help me somehow with it?

# Answer
> 6 votes
I have little experience using Unity directly, but I've been a level designer for years and a much easier approach rather than worrying about cutting holes into your terrain is to simply build up a C shaped ridge in your terrain for the size of your cave and then cover it with rock meshes to give it the illusion of a cave.

Another approach is that you could even forego pulling up the landscape all together and simply use the rock meshes to build the cave as this will likely look more realistic. I think using a terrain to actually form mountains and landscape is a very old-school approach to level design that no longer looks realistic. If using terrain, I only use it to form the ground you walk on and instead use rock meshes to build up the mountains, cliffs and caves/caverns and maybe the occasional sculpted terrain for the background mountains (though I even make these in Mudbox and World Machine and import them as a mesh.

If you're trying to create a system of underground Caverns that you can walk down into from your terrain, rather than cutting holes in the terrain, I would use meshes to form the mouth of the cave and then create a level transition point there that loads another map all together containing your caverns and then build the caverns entirely from rock meshes. Not only will this look better than trying to use a terrain to build the caverns, but you'll get better performance by making the caverns another level and using instancing on your rock meshes.

If creating a multiplayer map, I would either place the Cave mouths at the edges of my terrain and simply form the caverns using meshes that walk the player below the terrain mesh. OR you could add a teleport script at the back of the cave mouth that teleports you into the caverns below the terrain. There are a multitude of different approaches you could take to make the transition look seamless and still not need to actually cut holes in your terrain.

Something else to consider is that if you DO cut holes in your terrain, the LOD system will sometimes cause the holes to change in size and show gaps in the terrain where there shouldn't be. All in all, I don't ever recommend doing this as there are much better solutions as I outlined above.

---
Tags: unity, 3d, shaders, terrain, terrain-rendering
---


# Question
Title: Resolving prediction error from client side prediction and server reconciliation
I am writing a network game based on Gabriel Gambetta's articles on client-side prediction/server reconciliation. I have client-side prediction down (using Box2D for prediction) as well as server reconciliation (setting the predicted entity's physics state back and stepping up to the current client time, applying forces from input every step).

This, of course, results in desync; prediction error. My trouble is figuring out how to correct the prediction error. I've tried snapping 100% to the position from reconciliation, but this looks very jumpy. I've also tried changing the percent of the snapping (10%, 80%, 50%, 30%), but these look jumpy after a short time (since the error keeps increasing, the snap distance increases as well).

I've read that you are supposed to interpolate the current position with the position from reconciliation. But what are you supposed to interpolate between? Prediction occurs every frame, so there's no visual time to interpolate the position unless I send the entity back in rendering time, but that defeats the purpose of client-side prediction. Am I approaching this wrong?

# Answer
I solved the problem on my own. My previous implementation of the networking engine made reconciliation impossible. The code I am using is private, though I plan on open sourcing the Box2D server/client-side prediction eventually. My solution is as follows:

1. My game code is put into a separate custom Entity-Component-System, called NetEngine. The NetEngine *only* ticks with a fixed time step (the tick rate of my server, 33 ticks/second). Each tick increases a frame count, called frameNum, by 1.
2. Inputs are collected by clients and put into an InputSnapshot, which is sent to the server. InputSnapshots are collected at the server's tick rate. Each snapshot has a frame number attached to it (representing the server's ticks since the game has started). The client also saves snapshots for reconciliation later.
3. The NetEngine saves states of physics objects it controls (server = all entities, client = predicted entities) each frame. The frame number is attached to the snapshot. On the client, this is used for reconciliation, on the server it is used for lag compensation.
4. The server ticks the NetEngine when all the InputSnapshots from all players on all clients have been received, and sends the client updates on entities. The frame number is attached for reconciliation and interpolation. (ticking the engine is as follows: First, set the inputs of all entities to the snapshots. Second, tick the NetEngine. Third, send clients entity updates. Repeat this process until the NetEngine can no longer tick, aka when there aren't enough InputSnapshots).
5. Clients save PhysicsSnapshot for reconciliation.
6. When a PhysicsSnapshot for the player's entity is received, check the player's saved InputSnapshots. If the earliest saved InputSnapshot has a corresponding PhysicsSnapshot (by frame number), we can begin reconciliation.
7. Go through all entities and apply PhysicsSnapshots for the frame number found. Then, apply InputSnapshots for the player and tick the NetEngine. Keep applying InputSnapshots (and PhysicsSnapshots for entities that are not predicted) and ticking the NetEngine until the frame number has reached the current predicted frame number.
8. Remove the InputSnapshot used for that round of reconciliation.
9. Repeat the reconciliation process until no more reconciliation can be performed.

The client updates the NetEngine on its own (once every two frames, about, since my server runs about half as slow as my clients). In the client's Box2D simulation, all entities are kinematic except for predicted entities, which are dynamic. This allows the client to predict future states of its players, and check them again using the server's authoritative positions.

From what I have noticed, when this is implemented Box2D is fairly deterministic. I wouldn't bet on this, though, which is why I still run reconciliation.

It should also be noted that with the current setup (assuming interpolation is used), everything will render at 60fps except for the client's predicted players, which render at 33fps (the tick rate of the server). The fix for this, however, is to predict the next frame, and interpolate between the two frames. This fixes the client's players rendering at 33fps, and everything is smooth.

I did not describe lag compensation (I haven't implemented it myself), however there are many articles describing how. Essentially, the server keeps track of all PhysicsSnapshots and InputSnapshots, and because of this can rewind the state of the world in such a way that the server can recreate whichever client it chooses at any given time. The server is then able to determine if certain events have taken place (such as a player shooting another player, for example).

I apologize for the messy explanation, it's hard to describe server reconciliation in such a short response. However, if anybody has any questions regarding my method I'll be happy to answer them to the best of my ability.
> 6 votes

---
Tags: networking, client-server, interpolation
---


# Question
Title: 2 cameras that each player sees through a different one
Im very new to Networking in Unity 5. Im trying to bring the finished basis for my 2 player, 1 vs 1, turn-based game I made for local multiplayer (both players on same computer) to an online matchmaking system.

In the game currently (for local), there are 3 cameras. 2 centered on separate canvases for selecting attacks for each player.

that once p1 chooses his attacks and presses continue, the camera is deactivated and the 2nd camera for p2's attacks is activated. Once p2 presses to continue the 2nd cam is also deactivated

and the 3rd cam is put on, this camera is set on the battle arena and plays out in turns the moves picked by the 2 players through a turn-determining system.

What I want to do for the online is have both canvas cameras activated at the same time and each player to be assigned to a different camera. So is there a good way i should do this? NetworkView on one of the cams? Hope I explained the premise enough :P

# Answer
That's not how your online game will work. When playing on separate computers, you'll still only have one camera active at a time. There will be two instances of the game being run, clients A and B. A will have camera 1 active, B will have camera 2 active. The rest of the game world is synced between the clients.

It will be a lot of work to retrofit your local multiplayer game for online multiplayer if it's not designed for it.
> 1 votes

---
Tags: unity, camera, networking, unity-networking
---


title: Delay when moving elements

text:
# Question
Title: Delay when moving elements
How you can see my mouse goes little bit faster than widget.

My movement algorithm is:

```
cursorPositionPrev.set(cursorPosition);
cursorPosition.set(getCurrentPos());
...
Vector2f delta = new Vector2f(cursorPosition).sub(cursorPositionPrev);
widget.getPosition().add(delta);

```

I am using **LWJGL** and my own GUI solution.

Here is visual structure of event processor part. One thread for processing events generated by user and another thread render current gui state.

Even if rendering and processing events is in one thread the issue is still exist.

So what can I do to make to avoid this delay and make widget to keep up with the mouse movement?

# Answer
I found that the reason is my event queue realization and the second reason is that I use OS cursor (OS cursor is hardware accelerated).

Mouse position is current mouse position obtained from GLFW, lag - difference between current position from GLFW and from event system. Here is approve:
> 0 votes

# Answer
So, you say, that when you update the cursorPosition variable you update the cursorPositionPrev variable too. This is not a good idea and this could be one of the reasons why it goes a bit slower than your mouse.

Your update method gets called 60 times per second, but the mouse listeners can run way more times in a second.

So, let's imagine this: your mouse moves 3 pixels, you set the mouse position a the previous positions correctly.

The update method still doesn't run but the mouse moves another 3 pixels and the listener gets called again, you set the mouse position correctly, but the previous position will be wrong.

The update method runs and sees, that the distance between the previous position and the current position is only 3 pixels, while the user moved his mouse 6 pixels.

To solve this you need to move the line of code where you update your previous position to the end of the update method.
> 1 votes

---
Tags: java, algorithm
---


title: Can't load png in texture

text:
# Question
Title: Can't load png in texture
I created new project in libgdx without Android, specified for Eclipse. I added testcar.png to assests in core project, refreshed core and desktop projects,

```
new Texture(Gdx.files.absolute("C:\\TestGame\\desktop\\bin\\testcar.png"));
new Texture(Gdx.files.internal("testcar.png"));

```

gives

Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException:

Couldn't load file: C:/TestGame/desktop/bin/testcar.png at com.badlogic.gdx.graphics.Pixmap.(Pixmap.java:148) at com.badlogic.gdx.graphics.TextureData$Factory.loadFromFile(TextureData.java:98) at com.badlogic.gdx.graphics.Texture.(Texture.java:100) at com.badlogic.gdx.graphics.Texture.(Texture.java:92) at com.mygdx.screens.MainMenuScreen.show(MainMenuScreen.java:33)

but both those constructors work with jpg or gif(same folder as png) without any problem.

What i do wrong ? Is it bug?

# Answer
Strange bug, after slight editing of image, and saving image as png again, exception dissapper. During debug of application i saw TExture constructor call PixMap constructor and send FileHandle of file as argument, constructor read bytes from image (dont know correctly or with errors) then those bytes go to Gdx2DPixmap(bytes, 0, bytes.length, 0) and that constructor throws java.io.IOException: Error loading pixmap: decoder init failed for stream. That exception looks like as result of failed attempt to call native mehod load() in Gdx2DPixmap. So changing image somehow, was random but solution-creating idea.
> 0 votes

---
Tags: java, libgdx, textures
---


title: Elastically Object movement in unity3d

text:
# Question
Title: Elastically Object movement in unity3d
I want to move an object towards the destination elastically. Currently I am using Vector3.Lerp it working to move the object, start with high speed and reached at destination with low speed but missing elastic effects.

```
float i = 50, t = 0;
        while (t < 1)
        {
            t += Time.deltaTime / i;
            transform.position = Vector3.Lerp(transform.position, newPostionAtDistance, t);
            transform.LookAt(targetFollow.transform);
            if (transform.position.ToString() == newPostionAtDistance.ToString())
            {
                //StartCoroutine(CamElasticMoveBackEffetcts());
                Debug.LogWarning("Object reached to the point.");
                yield break;
            }

            smoothTime += Time.deltaTime;
            yield return 0;
            i++;
        }

```

# Answer
I haven't tested it but it seems you may want to use the `Berp` method from here, instead of Lerp.

```
public static float Berp(float start, float end, float value)
{
    value = Mathf.Clamp01(value);
    value = (Mathf.Sin(value * Mathf.PI * (0.2f + 2.5f * value * value * value)) * Mathf.Pow(1f - value, 2.2f) + value) * (1f + (1.2f * (1f - value)));
    return start + (end - start) * value;
}

```

You can modify the values to increase/decrease the 'shakiness'. The default ease function looks like this
> 2 votes

# Answer
If by elastic, you mean as though it was attached by a rubber band:

Whenever it passes the object, increase the force applied to it (with a maximum force of the remaining distance). To determine if it passes the object, you can check if the distance from the object increased since the previous frame. But be careful of performance issues.

As a side note, I'd be interested to hear more efficient alternatives.
> 0 votes

---
Tags: unity, c#, movement
---


# Question
Title: Protecting game assets through archiving
I'm writing a game in C++ (with OpenGL) and am getting quite far into development. Currently I'm loading the data directly from different directories.

(E.G. I load textures from a /Data/Textures/...png)

This is fine, but not preferable. Ideally I would like to protect these assets without too much of a performance hit. I looked at other games that I own, both Indie and AAA and found that the majority of them archive the data. However, I am unable to access these archives with programs like Winrar Archiver which implies that they have some level of protection.

I'm not particularly knowledgeable in the field of encryption and data storage, so I may be overlooking something obvious but I would like to know how exactly I could achieve something similar.

(I am aware that competent individuals are able to use the GPU to gain access to the data but that's not preventable)

# Answer
As others have said, there is no real protection for your assets. That doesn't mean you have to push them out there totally unprotected, though.

Having your own internal format for your assets is pretty useful or even necessary in the long run anyway. If you have your own file format that is not easy to open in content creation tools then it serves just as much for security as any kind of archive system.

You can do the same as well for image formats. I mean do you really want to store 80 types of files in a shipping game anyway? You can have an internal variable or encoding of some kind if you really want additional protection - or if you want to have the ability to have some files protected and others not.

I would make it so that you do not do this by default though, it is a serious drag for people working on your engine. Just allow for a deploy batch job that protects all the files for you before shipping.

A package is nice too so people can't even see file names, but it is pretty pathetic as a security measure, it just means you have put every file together and hidden the directory structure, really. So you make it harder on modders but don't really provide any security.

As for the issue of protection itself, I don't think it matters a lick if you are just putting a game out there. Why make it hard for people to mod whatever dumb stuff they want in there? Sometimes the mods can really help a game look better for that matter.

Yet you are probably going to need it eventually if you expect to have third party customers using things. Especially if you want people making various art packs for your engine. There's nothing that can really stop a determined thief but they won't make a pack for your engine at all unless you have some sort of provision to protect their work.
> 0 votes

# Answer
Sometimes resources seem inaccessible because the devs used customized or proprietary formats, I.E. appending sound effects to the end of sprite image file.

Keep in mind while it's possible to obfuscate the resources, but you can't fully protect them. Even if encrypted, your game will need to decrypt them before use & will need the key. If the key is in the game, the user can extract it. If the game gets the key from a server, the user can intercept it.
> 1 votes

# Answer
> I'm not particularly knowledgeable in the field of encryption and data storage, \>so I may be overlooking something obvious but I would like to know how exactly I \>could achieve something similar.

I don't know a ton of stuff about encryption or advanced data storage either. :)

However, one relatively simple way to protect the program assets would be to embed the data directly into the program. Instead of having an external "image.png", you could instead put the data representing that image into an array somewhere in your program. (A quick google search yields this). I'd suggest writing a quick program to convert from image to array. Anyways, once you have the image data stored in an array, you can simply load image data from there rather than the external image, eliminating the need to include the .png files with your projects.

Audio files could potentially be stored as binary data, but I'm not sure how that would work. Sorry. :(

Keep in mind that any changes to the image would require recompiling the file, and that if you have multiple large images the final program may be larger than it would be otherwise -- after all, you're storing the entire image inside the executable.

---

Apparently, if you're working on Windows then you can simply embed the assets as resource files inside the program, though I can't vouch for the ease or effectiveness of such a procedure: Stack Overflow post; MSDN link.
> 0 votes

---
Tags: opengl, assets, data
---


# Question
Title: Programmatically change combination of sprites
I am a total newby to unity and cannot figure out how to achieve the following:

I want to show a picture composed of different sprites. E.g., a pen with four binary features: the pencolor (black or silver), the penshape (ballpen or normalpen), an ornament (blue or orange), and the tintcolor (blue or black).

## My goal:

A function taking a numerical vector as input to specify which of the features/attributes of the pen to show.

* 0,0,0,0 = a black ballpen with blue ornaments and blue tint.
* 1,1,1,1 = a a silver normal pen with orange ornaments and black tint.
* ... and all combinations in between.

One constraint: I need to be able to change how many features there are, and how many values they take.

The sprites are stored in a sprite with mode "multiple" and I use unity to create the layers.

What I did so far:

## 1) Define an object holding the feature sprites

To enable changing how many features and feature values there are I created a structure. It has flexible length specifying the number of features. Each feature is sprite array specifying the number and source of the featuer values.

```
// New object class holding all visual feature sprites in hierarchical vectors
[Serializable]
public struct Feature
{
    public string Name;
    public Sprite[] FeatureValues;
}

public Feature[] Features;

```

This allows me to specify how many features, how many different sprites per feature, and to drag and drop the respective sprites onto the associated elements of the Features structure.

## 2) Defined a Prefab for the Pen

With the help of this post on displaying multiple sprites I created a prefab with as many layers as there are features of the pen

## 3. And now ... ?

Based on the first comment I created Sprite Renderers for all sub-elements of the Pen object.

The Pen object is a prefab.

Can anyone help me how to change the values of the sprite?

I am trying this: Based on the link mentioned above I create a new class for Pen objects with some sprite renderers

```
public class Pen : MonoBehaviour {

public SpriteRenderer Tintcolor;
public SpriteRenderer Casecolor;
public SpriteRenderer Ringcolor;
public SpriteRenderer Shape;

public void setTintcolor (Sprite featureImage)
{
    Tintcolor.sprite = featureImage;
}
public void setCasecolor (Sprite featureImage)
{
    Casecolor.sprite = featureImage;
}
public void setRingcolor (Sprite featureImage)
{
    Ringcolor.sprite = featureImage;
}
public void setShape (Sprite featureImage)
{
    Shape.sprite = featureImage;
}

```

}

Then I write a function to change the value of the sprite renderer.

```
// featureCombination is the vector holding the feature values to be displayed
public void ShowFeatureCombination(int[] featureCombination)
{
    Pen newPen = Instantiate(penPrefab) as Pen; // new Pen object

    newPen.setTintcolor(Features[0].FeatureValues[featureCombination[0]]);
    newPen.setCasecolor(Features[1].FeatureValues[featureCombination[1]]);
    newPen.setRingcolor(Features[2].FeatureValues[featureCombination[2]]);
    newPen.setShape    (Features[3].FeatureValues[featureCombination[3]]);
}

```

This does not work so far.

And it requires to manually specify the spriteRenderers, which i need to have automatically done based on the number of different features that I enter in the Feature structure.

# Answer
You should have a script attached to your Pen object.

Inside this script you have references (wether public or just visible in editor) where you drag the children via editor.

```
class YourPenScript {
    public GameObject Tint;
    public GameObject Case;
    public GameObject Ring;
    public GameObject Shape;

    private SpriteRenderer sr_tint;
    private SpriteRenderer sr_case;
    private SpriteRenderer sr_ring;
    private SpriteRenderer sr_shape;

    void Awake(){
        sr_tint = Tint.GetComponent<SpriteRenderer>();
        sr_case = Case.GetComponent<SpriteRenderer>();
        sr_ring = Ring.GetComponent<SpriteRenderer>();
        sr_shape = Shape.GetComponent<SpriteRenderer>();
    }

    public void ShowFeatureCombination(int[] featureCombination){
        /* here you should apply your logic to pick features and apply sprites*/
    }
}

```

In this way you have a class with references to desired components. Now you can apply your logic to pick sprites from the features.

**EDIT**:

To fit your needs of dynamic feature number you have to create at runtime al the gameobjects needed by your pen.

consider having an initialization function like

```
public void Initialize(int[] featureCombination){
    foreach(Transform t in newPen.transform){
        if(t!=newPen.transform) Destroy(t.gameObject);
    }
    ShowFeatureCombination(featureCombination);
}

```

with consequent change to your function

```
public void ShowFeatureCombination(int[] featureCombination)
{
    Pen newPen = Instantiate(penPrefab) as Pen; // Move this to awake and make newPen a class variable

    for(var i = 0; i < featureCombination.Length; i++){
        GameObject f = new GameObject();
        f.AddComponent<SpriteRenderer>();
        //insert your logic to apply sprite
        /*maybe f.GetComponent<SpriteRenderer>().sprite = _spriteRenderers[i]; ?*/
        f.transform.parent = newPen.transform;
    }
}

```
> 1 votes

---
Tags: c#, sprites, image
---


# Question
Title: Is 3d game development advantageous/possible in SDL2?
I think this is not appropriate, but as the given video in the link, the youtuber name Bisqwit creates his own 3d engine from scratch in C and SDL2. How much is this advantageous is real 3d game development and following his idea can a first practice project? (rather than just starting with OpenGL)?

https://www.youtube.com/watch?v=HQYsFshbkYw

# Answer
Your question needs re-phrasing. SDL and OPENGL are two different technologies so to speak. Also, this question will lead to opinions instead of facts

Wikipedia says: Simple DirectMedia Layer (SDL) is a cross-platform software development library designed to provide a low level hardware abstraction layer to computer multimedia hardware components.

Open Graphics Library (OPENGL) is a cross-language, cross-platform application programming interface (API) for rendering 2D and 3D vector graphics.

You do not just start with OPENGL and create a game. The workflow for creating a game using OpenGl is as follows: 1- Create a window on your platform of choice. For Windows this will be with, in my case SDL, SFML or GLFW. These are also available on Mac, Linux, IOS and Android with the exception of GLFW. GLFW does not support mobile platforms last i checked. 2- Create an OPENGL context that you can render to. This step depends on your Language choice. In C++ you get these out of the box for SDL, SFML and GLFW. In C# you need another tool like The Tao framework. 3- Call OpenGL functions and render vertices. These steps are only three but doing all this and learning the tools will take you months even if you are a seasoned developer.

So, you can use SDL for Window creation, handling input, object loading and networking(I left out some). You will need the features that SDl provides to even draw a triangle on screen. You can use GLFW, SFML,GLUT or other similar tools out there but you have to start here. You can make do without these tools but creating a window in C++ on windows in my case is not an easy task.

Checking the SDL home page tells me that Half Life 2 was made with SDL. I also read somewhere that World of Warcraft most likely uses SDL. (Here similar qeustion about game engines). That question and specifically the second answer should address a lot of follow up questions that you will have.

Looking at how you asked your question I would have to make the assumption that you have never made a game at all. Your question is aimed at the lowest level of game development, graphics programming. I would suggest you go with a 2D framework first and make Breakout, Tetris, Snake clones. A non exhaustive list is SFML, SDL2, Monogame, XNA. Making something this simple will teach you a lot.

If your target is 3D graphics then go for Unreal, Unity, Torque, NeoAxis, JMonkeyEngine, Panda3D, Irrlicht. Stay away from Ogre unless you really know what you are doing. All the frameworks and engines I listed have bindings/wrappers for multiple languages.

TLDR: You will need SDL, SFML, GLFW or GLUT and other similar(Google them) frameworks to create a window first. Then setup an OPENGL context before you can draw vertices.
> 7 votes

---
Tags: sdl2
---