title: how to automate the game testing?

text:
# Question
Title: how to automate the game testing?
I am new into this field of testing. I just developed a basic game using unity engine but i want to test it.

I have checked with selenium but i don't know how to get the value that is being returned which has the information of the action that is being performed in the game. If i am able to get the value then i will be able to take necessary action accordingly.

# Answer
There are multiple ways to test a game, two most used are: unit and integration testing.

For **unit testing** you're testing the inner workings of the game, without actually running it. You can do this for specific modules which have dependencies abstracted away (e.g., logic that computes the Quest XP you get, based on a given set of factors; whether a given sound is played). Depending on how much you abstract your logic, you could test more, but for unity specifically, it might be harder given the way the game architecture is done (e.g., inheriting from monobehaviour). Nevertheless, applying OOP patterns like composition, you can extract bits of logic that can be tested in a deterministic way (e.g., physics), even if sometimes it can be seen as a bit extreme. It all depends on how much time you have, whether you started from scratch with the project or not, how much experience you have, etc. In general, I haven't seen much unit testing in games compared to the other non-game software projects. This kind of testing is quite easy to automate as you provide mocked behaviors that you simulate.

For **integration testing**, you interact with the "whole" game at a given time, when all parts are running. Depending on the depth of things you want to test, I see it might be very easy to outright impossible.

One idea would be to have an "integration test" build, which logs *every* (most) actions it does (i.e., spawning monster, playing sound, starting effect, spawning particle). After it runs for a given time, you can check the logs to see whether it matches a given pattern (this also depends on how random the game is, based on the inputs). Now, this sounds simple, but the question is: how you tell the game to do the wanted actions? Which brings me to the second idea.

Other idea would be to have kind-of server in the game, again, for testing purposes, which is able to process requests (e.g., via a REST API), and which acts upon the entities. The requests could be things like: move left, jump, rotate X degrees, change viewport, etc. With this approach you can also do the "checks" that the game is acting as expected, either by checking state directly, or verifying a virtual log of events that happened. This approach is used by other UI-testing tools for mobiles (e.g., Xamarin Test Cloud)

For the controlling part, if your game is touch/browser based, you can instead simulate the actions via a virtual touch/input device, but this is a bit more hard, depending on the actions complexity.

Another idea, with regards the visual aspect, is to take some reference screenshots, images during an initial phase, and comparing them after the same action sequence happened on a newer build. The comparison can have a specific deviation allowance, to guard against minor changes. During the tests, you can log the screens that didn't match and see the difference. It may be the case that the reference screens need to be updated due to different changes. In that case the game could be run again with the preset actions, and reference images be updated. This will probably not work very well with particle systems, or randomly-generated scenes, unless you use the previous idea to set some sort of seed, that is used to generate the particles.

For the sounds, it might be a bit harder, cause it will involve "listening" to the OUT device (which is not always possible IIRC, since it depends on the hardware of the system). But if it's possible you can do the same reference-based comparison as you do with the images.

I hope this sheds some light on how you could automatise the game testing.

Later Edit: I just see that there was another related question which might give you some pointers on how you'd do certain bits: Automated testing of games
> 1 votes

---
Tags: unity, testing
---


title: LibGDX - FPS drops

text:
# Question
Title: LibGDX - FPS drops
I've been trying to record some gameplay footage of the game I'm currently working on, using the Android SDK and ADB to do it.

Whilst the game runs at constant 60 fps in my medium-end phone, as soon as i start recording, it drops to around 50-55 fps, but always inconsistent. Now, I know that screen recording does "push" harder for the phone and thus may bring the fps down, but I'm worried that, because of this behavior, lower end smartphones will also have these lag issues - which shouldn't happen, as it's a relatively straight forward 2D game.

After performance testing for a while, I figured out that the major cause of lag are the "background elements": being a side-scroller, I have a list that holds 4 of these background elements (which are just textures retrieved from an atlas). As the camera goes further, I then update the position of those textures, so they also appear further, like so:

```
private List<Mountain> mountains;
// ...
mountains = new ArrayList<Mountain>(4);
for (int i = 0; i < 4; i++) {
        mountainPos = new Vector2(20 + 100 * i, 150);
        mountainColor = Color.BLACK;
        mountains.add(new Mountain(
            mountainPos, 350, 250, "texturePath", mountainColor));
// ...
// On the update method, I update the positions.
for (int i = 0; i < 4; i++) {
    // If the mountain can't be seen by the camera...
    if (hero.getPosition().x - mountains.get(i).getPosition().x >= 500) {
        highestMountainX += 100;
        mountains.get(i).setPosition(new Vector2(
                highestMountainX,
                mountains.get(i).getPosition().y)
        ));
   }
}
// ...
// On the render method
for (int i = 0; i < 4; i++)
    mountains.get(i).render(batch);

```

So, this leaves me with *two* questions:

**1.** Roughly, should I be worried about lag issues on lower-end smartphones, considering the fps drops I get while recording in my medium-end one?

**2.** The sprites I mention above are 350x250 pixels, and are rendered with that same width and height (350 and 250, respectively). Is the position updating method above inefficient? Any optimizations I could do?

Thanks in advance.

EDIT 1: Not sure if this is relevant, but the spritebatch's total render calls, everytime the render method is called, ranges from 4 to 14 (during the play state).

# Answer
You should avoid invoking new instances in your render and update methods. As these methods are called numerous times per second, this can be a pretty straining task, as the unreferenced instances will have to be freed in memory through garbage collection. To solve the two Vector2 problems, easy:

Declare and instantiate two global Vector2 attributes, and change your code to:

```
//first Vector2
mountainPos = firstGlobalVector.set(20 + 100 * i, 150);

//second Vector2
mountains.get(i).setPosition(secondGlobalVector.set(
                highestMountainX,
                mountains.get(i).getPosition().y)
        ));

```

As I do not know how your Mountain class is constructed, I cannot directly help you avoid the continuous invocation of new Mountain instances. Just try to solve it in the same manner as we've solved the Vector2 problems. Avoid new instances, and try to **update** already existing instances.
> 3 votes

---
Tags: java, libgdx, first-person-shooter, screen, lag
---


# Question
Title: Can't get to work Spritefonts on monogame 3.5(using Visual Studio 2015 Comunity)
I've been trying to get to work spritefonts, but to no avail. I've added the pipefont to the Pipeline

but when I try to load it, it shows this error here

Here it is the spritefont content

```
<?xml version="1.0" encoding="utf-8"?>

```

```
<!--
Modify this string to change the font that will be imported.
-->
<FontName>Arial</FontName>

<!--
Size is a float value, measured in points. Modify this value to change
the size of the font.
-->
<Size>12</Size>

<!--
Spacing is a float value, measured in pixels. Modify this value to change
the amount of spacing in between characters.
-->
<Spacing>0</Spacing>

<!--
UseKerning controls the layout of the font. If this value is true, kerning information
will be used when placing characters.
-->
<UseKerning>true</UseKerning>

<!--
Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
and "Bold, Italic", and are case sensitive.
-->
<Style>Regular</Style>

<!--
If you uncomment this line, the default character will be substituted if you draw
or measure text that contains characters which were not included in the font.
-->
<!-- <DefaultCharacter>*</DefaultCharacter> -->

<!--
CharacterRegions control what letters are available in the font. Every
character from Start to End will be built and made available for drawing. The
default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
character set. The characters are ordered according to the Unicode standard.
See the documentation for more information.
-->
<CharacterRegions>
  <CharacterRegion>
    <Start> </Start>
    <End>~</End>
  </CharacterRegion>
</CharacterRegions>

```

Any ideas?

# Answer
> 0 votes
To be honest I don't really use SpriteFont's myself. I prefer to generate BitmapFont's using BMFont and importing them in with MonoGame.Extended (I'm the creator of that library).

That said, I think I can see the issue pretty quickly. You haven't got an *importer* or *processor* set in the Pipeline tool.

When I add a sprite font to the Pipeline the properties window looks like this:

As you can see, the *Build Action* is set to *Build* and the importer and processor is also set. This happens by default when you add a new spritefont within the tool.

If you right click the root Content node in the tree and select Add =\> New Item...

You should see a window like this:

That'll generate a new SpriteFont file and you can open it up in a text editor to change the font. Here's what it looks like on my machine:

```
<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">

    <!--
    Modify this string to change the font that will be imported.
    -->
    <FontName>Arial</FontName>

    <!--
    Size is a float value, measured in points. Modify this value to change
    the size of the font.
    -->
    <Size>12</Size>

    <!--
    Spacing is a float value, measured in pixels. Modify this value to change
    the amount of spacing in between characters.
    -->
    <Spacing>0</Spacing>

    <!--
    UseKerning controls the layout of the font. If this value is true, kerning information
    will be used when placing characters.
    -->
    <UseKerning>true</UseKerning>

    <!--
    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
    and "Bold, Italic", and are case sensitive.
    -->
    <Style>Regular</Style>

    <!--
    If you uncomment this line, the default character will be substituted if you draw
    or measure text that contains characters which were not included in the font.
    -->
    <!-- <DefaultCharacter>*</DefaultCharacter> -->

    <!--
    CharacterRegions control what letters are available in the font. Every
    character from Start to End will be built and made available for drawing. The
    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
    character set. The characters are ordered according to the Unicode standard.
    See the documentation for more information.
    -->
    <CharacterRegions>
      <CharacterRegion>
    <Start> </Start>
    <End>~</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>

```

I hope that helps. Good luck :)

---
Tags: monogame, visual-studio
---


# Question
Title: Is it possible to debug a Unity Android game directly on a device?
I'm working on my game and every time I make changes to it I send the game to my mobile device to debug it.

I want to know how I can directly debug my game using an Android device instead of the MonoDevelop editor?

# Answer
Your question is pretty unclear. If you want to use your Android device to control the game, you can set up a connection with Unity and your device through USB, using the Unity Remote app: https://play.google.com/store/apps/details?id=com.unity3d.genericremote&hl=bg

That way you don't have to wait for it to build and push to your device for every small change in your game.
> 1 votes

---
Tags: unity, android, debugging
---


# Question
Title: How to implement a configurable spring force to SpringJoint2D like SpringJoint does?
I'm working in unity 5.3.4f1.

Looking at the SpringJoint2D class I can't seem to find a similar "spring force" as in spring in SpringJoint.

Is there any other way to make a spring stronger in SpringJoint2D?

If not, the only option I see is to inherit the Joint2D parent class and build my own spring joint 2D.

# Answer
I found a good way around. You can use DistanceJoint2D, get the reaction force and build your own spring model by doing F/K = x where x is the distance travelled away from the natural distance and K is your spring constant.
> 1 votes

---
Tags: physics, unity
---


title: Add points to a prefab in Unity

text:
# Question
Title: Add points to a prefab in Unity
I have a prefab that looks like this:

I have created a couple of 'points' in the Hierarchy using 'Create Element' and I would like to attach them to the prefab, however drag and drop over doesn't work. Why is that?

# Answer
> 1 votes
It is a little unclear what you are trying to do. If those points you created are empty GameObjects and you want them to be child objects of the prefab then you simply drag the prefab into your scene and then child your points under the prefab. Then all you have to do is hit the apply button in the inspector on the prefab parent and those points will then be part of the prefab. You can then delete the prefab from your scene as it is already saved in your prefab file. If you want to drag your points into a script on your prefab, I don't believe that is possible. You will have to find another way in your script to find the points without using the inspector, ie. using findGameObjectsWithTag(). Hope this answered your question. :)

---
Tags: unity
---


# Question
Title: How do I implement a hit box system in a fighting game?
In a fighting game, a move that you execute is basically just a series of hit boxes that are enabled and disabled at certain times. I want to know how do you create this hit box system.

I have no idea as to how to make a flexible system where I can enable and disable a hit box on any frame of a move and also add additional frame data. All I can think of is having a list that is the size of the amount of frames of the move, and add all of the enables, disables, and frame data as one list item. The problem with that is that a list item can only be one object, so I have to somehow make all my frame data and hit box enables & disables into one object. If I can have as many hit boxes in a move as I want then this list item object needs to have a list as well, which I don't think is a good way of doing it.

So, I just want to know a good way of implementing a hit box system in a fighting game.

# Answer
> 2 votes
There's a couple of ways you could go about such a system, as with anything. I'll try to describe the core of one such system in a pretty general sense here:

An animation consists of AnimationFrames. An animation frame contains a bunch of data.

```
struct AnimationFrame
    {
    //The graphic for this frame
    Sprite * sprite;

    //Duration (for example, in milliseconds)
    unsigned int duration;

    Hitbox hitboxes[N];
    Hitbox hurtboxes[N];
    };

```

So each frame has a list of hitboxes and hurtboxes. Inside the game, they would look like something like this: http://ensabahnur.free.fr/BastonNew/hitboxesDisplay.php?sMode=f&iChar=2&sMoveType=fd\_normals&sAction=w&iMove=6

What, then, is a hitbox or a hurtbox? Of course its a rectangle with four values (offsets from the character's world position), but it also holds additional data.

Every frame you will be polling whether each hitbox of each character's current animation's current frame collides with a hurtbox of another character. But what happens when the rects do collide is up to the hitbox. There's a couple of ways to imlement this. Say you have a generic hitbox struct:

```
struct Hitbox
    {
    int x, y, w, h;
    //...other data
    };

```

What is the other data in addition to the rectangle's dimensions? It could be a function pointer (say, to a function that deals damage to the current opponent.) It could also be an integer ID. Each Strike or Ability a character had would define what happened if a Hitbox of a given ID during a certain frame collided. Additionally, the AnimationFrames themselves could have an ID, a function pointer or similar event appointed to them.

Lastly, each animation is simply a list of AnimationFrames. Its up to other systems how these are updated or handled.

I hope that gives you at least some ideas.

# Answer
> 0 votes
What comes to my mind would be to have a list of each collision box per frame of the attack, then advance each hit box every frame and check if it collides with any enemy. If so, set the attack hit to true so the enemy doesn't get hit twice or more times for the same attack. If this doesn't make sense, here's an example of the code in Java:

```
public void updateEntity()
{
    if(isAttacking && !attacked)
    {
        if(attackFrame++ < attackBoxes.length)
        {
            for(int i = 0; i < entities.size(); i++)
            {
                if(entities.get(i).bounds.intersects(attackBoxes[i]))
                {
                    attacked = true;
                    entities.get(i).damage(...);
                }
            }
        }
        else
        {
            attacked = isAttacking = false;
            attackFrame = 0;
        }
    }
}

```

The attackFrame variable is also what you can use to render each animation frame for the attack. The attackBoxes variable can be an array to hold each collision box for each frame, which you will have to set on each attack.

---
Tags: collision-detection, software-engineering, fighting-game
---


# Question
Title: How can I run my LÖVE game directly from the Lua interpreter?
I've just started with LÖVE and Lua. I'm interested in LÖVE because I want to play around with something different from my day job (I'm a web developer). Since it uses Lua and is interpreted, I thought it would be a great way to try out the API.

But I couldn't figure out how to run my LÖVE game directly from the Lua interpreter. I'm finding it bothersome to package the game each time I make a little test with the API.

# Answer
> 8 votes
LÖVE isn't as a library that you import into Lua. What it does is embed the Lua interpreter and expose its game functionality to that interpreter.

If you'd like to interactive play with the API, there's a couple of libraries built for debugging and live coding:

Source: https://love2d.org/forums/viewtopic.php?t=8537&p=52985

**\[EDIT\]** The debug function can also be useful in a limited context.

**\[EDIT EDIT\]** The love-console library was apparently built on an older version of LÖVE, but at least it's a starting point for building your own prompt.

If you're not specifically looking to work with Lua and a game-centric SDL-based framework, another fun one to try out is ruby-processing. It wraps JRuby, making it more convenient to access the Processing library, and has a mode where it will watch a sketch and recompile it every time you save the file. There's also a "live coding" mode but I haven't gotten it to work for me.

**\[EDIT x 3\]** Also look at PyProcessing. It has the advantage of having to not bundle JRuby, and can be imported into a standard python interpreter (provided you have all the dependency modules installed, which is Pyglet (which requires PyObjC on OS X).

# Answer
> 3 votes
To run a game you made in Löve2D, you have to drag its folder (the one containing the main.lua) to the Love2D executable. It's the easiest way to run it. If you want to export you game into an executable itself, you have to package the folder and embed it into the Love2D executable.

If you made a .love file, the same applies, just drag the .love file to the Love2D executable. Make sure main.lua is in its root folder, though. If you installed Love2D in your computer instead of running its portable version, you should be able to play it by just double-clicking the .love file though.

# Answer
> 2 votes
I'm not sure it counts as running it through the lua interpreter, but you should be able to run it without packaging:

On a terminal, navigate to the directory with your main.lua file, and just enter "love ."

I'm pulling that from memory, but this is where I found it originally: Love wiki

# Answer
> 2 votes
Here's what I did that works for quick running.

I created a main.lua file which has only one line

```
require('main2')

```

I put that file in a zip by itself, gave it the .love extension, and put it in the root of my project folder. Now, I can just double click that whenever I need to test.

Then, main2.lua is my actual main file. You don't even need to make the actual main file a proper module. Writing the love.load(), love.update(dt), and love.draw() functions will write to the global definitions.

# Answer
> 1 votes
If you're not "married" to a particular editor, I really recommend ZeroBrane Studio IDE: It's open-source, implemented in Lua itself (using wxLua), very lightweight but also very powerful and convenient.

ZBS allows you not only to re-run your code with a single keypress, but also to debug it and even do "live-coding" for Löve and a few other game frameworks.

I've been using it for a few weeks now, and can wholeheartedly recommend it.

---
Tags: lua, love2d
---


# Question
Title: Unity - resizing particles dont mantain collisions properly
I am trying to make particles for blood on death. This is what I got so far:

Which looks fine and all. But now I also wanted to make the blood particles turn smaller over their lifetime, so I checked "Size over lifetime" and this is what happens now:

See the problem? As they shrink, they seem to float a little, giving some space between the floor they are laying on. This behaviour is not really desired.

How could I solve this?

# Answer
> 2 votes
Reduce the radius scale value as needed. Tweak how near you want the particles with the value.

You can change `particleSystem.collision.radiusScale` in runtime to avoid sinking.

---
Tags: unity
---


# Question
Title: Respawn not working properly upon scene reload. Why is this?
So I made a respawn function and what is supposed to happen is the script it supposed to load a saved checkpoint. However I need to reset the scene (and again this worked just fine last night which was odd...).

Essentially the checkpoint waits for a player and then when the player enters the current checkpoint is written to a .txt file. Upon reload or death the scene is restarted, the .txt file is read and grabs the checkpoint. Everything works fine without `Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene.name); //Reload scene.` but I need that in order to "refresh" the scene.

CheckPoint Code:

```
using UnityEngine;
using System.Collections;

public class Checkpoint : MonoBehaviour {

    public LevelManager levelManager; //Empty level manager.

    // Use this for initialization
    void Start()
    {
       //levelManager = FindObjectOfType<LevelManager>(); //Unnneeded
    }

    void OnTriggerEnter(Collider coll)
    {
        if (coll.tag == "Player")
        {
            //levelManager.currentCheckPoint = gameObject; //<-DISABLE WHEN ES2 is fixed!!!
            Debug.Log("Activated Checkpoint " + transform.position);
            ES2.Save(gameObject.name, "myFile.txt?tag=checkpoint"); //Saves checkpoint to file.
        }
    }
}

```

LevelManger Code:

```
using UnityEngine;
    using System.Collections;
    using UnityEngine.SceneManagement;

    public class LevelManager : MonoBehaviour {

        [Tooltip("Note this will also serve as the spawnpoint for the player!")]
        public GameObject currentCheckPoint;
        private GameObject player;
        private int PHP;
        public int RespawnHP; //Amount of health to give player upon respawn.

        void Awake ()
        {

        }

        // Use this for initialization
        void Start ()
        {
            player = GameObject.FindGameObjectWithTag("Player");
        }

        // Update is called once per frame
        void Update ()
        {
            PHP = GameObject.Find("InventoryManager").GetComponent<InventoryManager>().PlayerHealth;

            if (PHP <= 0)
            {
                Debug.Log("Player HP has been depleted. Respawning.");
                RespawnPlayer();
            }

            if (Input.GetKeyDown("r"))
            {
                Debug.Log("Restarting level!");
                RespawnPlayer();
            }
        }

        public void RespawnPlayer()
        {
            Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene.name); //Reload scene.
            currentCheckPoint = GameObject.Find(ES2.Load<string>("myFile.txt?tag=checkpoint")); //Load saved checkpoint.
            Debug.Log("Player Respawning...");
            player.transform.position = currentCheckPoint.transform.position;
            GameObject.Find("InventoryManager").GetComponent<InventoryManager>().PlayerHealth = RespawnHP;
        }

        void RestartLevel()
        {
            //ToDo: Restart level, and reload last check point.

        }

        public static void SaveLevel() //Saves the current level to file.
        {
            //ES2.Save(SceneManager.GetActiveScene().name, "myFile.txt?tag=levelName"); //Saves level to file.
            //ES2.Save("none", "myFile.txt?tag=checkpoint"); //Overwrite checkpoint?
        }
    }

```

Does anyone have a clue what is wrong? Like I said earlier the problem seems to arise on scene reloading.

Response to comment(s):

> What behaviour are you observing at the moment? - Jack

Currently what happens is the player enters a checkpoint, the checkpoint is saved to a file, and upon respawn the checkpoint is loaded. After this I get spawned to the checkpoint that was saved but then immediately the level reloads itself and the player is not respawnd at the checkpoint. Here is a video to better demonstrate the issue (it will take a minute or two to finish up processing here as I've just pasted the link).

# Answer
In your `RespawnPlayer()` method you are loading a scene at first. Then checking current position, then translating the player to the checkpoint.

Upon loading a new scene, everything resets. In `RespawnPlayer()` after second line execution, the level manager restarts from `Start()` ignoring the current checkpoint and player translate codes in `RespawnPlayer()`. In my first solution **I just took three line from your `RespawnPlayer()` and put them `Start()`**. Another line is just precaution.

Set your player object's position at `Start()`.

Changes in your LevelManager script:

```
void Start ()
{
    player = GameObject.FindGameObjectWithTag("Player");
    //Get current checkpoint from file
    if(emptyFile)
    {
    currentCheckPoint = vector3.zero;//or default position
    }
    player.transform.position = currentCheckpoint.transform.position;
    //Set health value to player
}

public void RespawnPlayer()
{
Scene scene = SceneManager.GetActiveScene();
SceneManager.LoadScene(scene.name);
}

```

Or Instantiate your player at `Start()`. It's handy when you control multiple levels from Level Manager. Keep your "player" named prefab at Resources folder.

```
void Start ()
{
    //Get current checkpoint from file
    if(emptyFile)
    {
    currentCheckPoint = vector3.zero;//or default position
    }
    Instantitate(Resources.Load("player"), currentCheckpoint.transform.position, Quaternion.identity);
    //Set health value to player
}

```
> 2 votes

---
Tags: unity, c#, scene, scenemanager
---


# Question
Title: Setting Window Icon Using GLFW (LWJGL 3)
What's the best, cross platform, way of setting the window icon using LWJGL 3?

I have a PNG image and would like to set it to the icon present in my dock (OS X) or the application bar (Linux).

# Answer
They added it to build 79, the method is called: glfwSetWindowIcon(long window, Buffer images);
> 1 votes

# Answer
I have found an answer!!! After searching far and wide through the depths of the internet, I have found the following method. It works perfectly!

```
    public void setIcon(String path) throws Exception{
    IntBuffer w = memAllocInt(1);
    IntBuffer h = memAllocInt(1);
    IntBuffer comp = memAllocInt(1);

    // Icons
            {
                ByteBuffer icon16;
                ByteBuffer icon32;
                try {
                    icon16 = ioResourceToByteBuffer(path, 2048);
                    icon32 = ioResourceToByteBuffer(path, 4096);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                try ( GLFWImage.Buffer icons = GLFWImage.malloc(2) ) {
                    ByteBuffer pixels16 = STBImage.stbi_load_from_memory(icon16, w, h, comp, 4);
                    icons
                        .position(0)
                        .width(w.get(0))
                        .height(h.get(0))
                        .pixels(pixels16);

                    ByteBuffer pixels32 = STBImage.stbi_load_from_memory(icon32, w, h, comp, 4);
                    icons
                        .position(1)
                        .width(w.get(0))
                        .height(h.get(0))
                        .pixels(pixels32);

                    icons.position(0);
                    glfwSetWindowIcon(window, icons);

                    STBImage.stbi_image_free(pixels32);
                    STBImage.stbi_image_free(pixels16);
                }
            }

            memFree(comp);
            memFree(h);
            memFree(w);

}

```

And the "ioResourceToByteBuffer" method is in a class that contains this:

```
    private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
    ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
    buffer.flip();
    newBuffer.put(buffer);
    return newBuffer;
}

/**
 * Reads the specified resource and returns the raw data as a ByteBuffer.
 *
 * @param resource   the resource to read
 * @param bufferSize the initial buffer size
 *
 * @return the resource data
 *
 * @throws IOException if an IO error occurs
 */
public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
    ByteBuffer buffer;

    Path path = Paths.get(resource);
    if ( Files.isReadable(path) ) {
        try (SeekableByteChannel fc = Files.newByteChannel(path)) {
            buffer = BufferUtils.createByteBuffer((int)fc.size() + 1);
            while ( fc.read(buffer) != -1 ) ;
        }
    } else {
        try (
            InputStream source = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
            ReadableByteChannel rbc = Channels.newChannel(source)
        ) {
            buffer = BufferUtils.createByteBuffer(bufferSize);

            while ( true ) {
                int bytes = rbc.read(buffer);
                if ( bytes == -1 )
                    break;
                if ( buffer.remaining() == 0 )
                    buffer = resizeBuffer(buffer, buffer.capacity() * 2);
            }
        }
    }

    buffer.flip();
    return buffer;
}

```
> 2 votes

---
Tags: java, lwjgl, glfw
---


title: understanding game networking

text:
# Question
Title: understanding game networking
I have been working on a real-time game, and am closing in on the point where I send and receive data. I have previously accomplished this before with a couple other test games, but I have never really learned the correct way to pass data from server to clients efficiently.

My question: What is the best practice for a real time game to pass data? I have my doubts that I should be sending an update every frame (currently running at ~30 fps), but in all honestly I dont know what is best.

Most of the games ive worked on have passed the data instantly when they happen and continue to update every frame. Any suggestions or advice? Ill post more info if needed as well.

Thank you

# Answer
> 1 votes
In multiplayer networked games, exchanging information among clients and server, dealing with synchronization, update every client at a proper rate, and all other stuff about game networking, they make up a **game network protocol**, thus the rules adopted by such game to deal with the so-called netcode. So, the right question to ask is:

**How do I set up a network protocol for my game?**

Building a game network protocol, and dealing with game networking in general, is not a simple task. A fast-paced game such as an FPS may use a different net protocol compared to the one used by a RTS game, because of some aspects:

* **Data quantities:** the quantity and quality of data exchanged between any client and the server depends on the complexity of a game. A simple FPS - where you are required to move and shoot only - will require less data than another FPS where much more user interaction is required, like using grenades, switches, vehicles, platforms, chat. Also, an RTS will deal with different kind of data, because there are less players but many more objects to keep track of, whence more data to exchange.
* **Synchronization rate:** a RTS doesn't need constant updates to keep the clients on sync, as there are limited actions from the players over the time; on the other hand, an FPS requires fast action, and any player may move, shoot, interact, or die at any time, and you need to make sure *every* other player can see it as soon as possible.
* **Reliability:** ideally, we may have a game where no packets are lost when sent. This is not a real scenario, so we must distinguish between data packets that *need* to get *always* to the clients (or server), and data that can be lost when sent without harming the gameplay or the user experience with the game. In FPSs and RTSs there are different type of packets which belong to the former or the latter category, still this depends on the complexity of your game.
    + Example 1: you order an ally unit to attack an enemy unit, and the enemy unit dies. This *must* be notified to all other players; if information is lost, we send it again until the client tells us the packet has arrived.
    + Example 2: you write a message to the global chat. You don't read the message on the screen because it was lost. We may choose to send again the packet, or let the player just write the message again.

Other aspects are more or less common to game networking in general. In any game you must deal with players' bandwidth, application throughput, in-game timestep, lag detection, client-side prediction and server-side correction, congestion avoidance...

To answer your question, sending game updates at a high rate is not good or bad: it depends on the type of game. In a chess game you don't need nothing special but sending updates every time a move is performed; in an FPS, you may want to send updated 20 to 60 times per second, because anything can happen at any moment.
If your game runs at 30 fps, you can choose to keep this rate or lowering it if the gameplay doesn't break at all. You can change its values and test the overall performances.

Network Programmer Glenn Fiedler wrote, and is still writing, very interesting articles about game networking, building a game protocol, and dealing with networking issues (congestion, packet loss, compression) on its site: gafferongames.com. I suggest you to give a read to his articles, like Sending and Receiving Packets where he explains the many aspects of data input/output in a networked game.

---
Tags: networking, game-maker
---


title: How to create Half hemisphere 3D model

text:
# Question
Title: How to create Half hemisphere 3D model
I already have an `hemisphere.obj` 3D model. But I'm trying to build a half-hemisphere (quarter sphere) model. How can I do that? What is the easiest way to do that?

Generally, is there any easy way to create 1/n of sphere?

# Answer
> 7 votes
If you just need it once, I'd suggest you pick up some basic knowledge of a modelling tool. It's very easy to do in Blender:

1. Delete the cube that you start with by pressing `DEL`.
2. Create an `UV Sphere` primitive. This will create a sphere with radius 1.0
(Note: In the lower left corner you can edit the properties (segment/ring count, radius) of the sphere after creation.)
3. Change view to `Front` and zoom in using the mouse wheel:
4. Press `TAB` to enter edit mode. Press `a` to clear the selection (which is orange).
5. Change the display mode to wireframe (so we can select stuff that would be hidden behind the front surface):
6. Press `b` and you'll get a selection rectangle. Select all vertices you want to remove:
7. Press `DEL` and select `Vertices`.
8. For a quarter-sphere: Change view to `Top` like in step 3 and repeat steps 6 and 7.
9. Once you're done editing, hit `TAB` to exit edit mode.
10. Change shading to `Smooth` so you get interpolated normals:
11. Select `File -> Export -> Wavefront (.obj)`.

# Answer
> 0 votes
Maya experience here. Use a plane or cube to insect with your object. Use boolean operation like UNION,difference, etc to get this.

---
Tags: 3d, unity, 3d-meshes, 3d-modeling
---


# Question
Title: What formula is commonly used in rpg based games to calculate gained currency?
Assuming I have an RPG game with monsters, a game you can fight any amount of monsters at any time - What are my options for a gained currency from a battle formula? I've been trying to use Google for any ideas, but couldn't find something solid.

Currently I have the `enemy level` * `user level` * `0.1`

Pretty sure I need something more realistic and randomized, Hope someone can share any idea about it.

Thanks in advance!

# Answer
There is no common formula because the formula depends on your game design goals.

In the end the worth of money is the worth of what you can buy with it, so you always need to think of money rewards in terms of the items it is worth (usually. there are of course games where making money is a goal in itself, but I don't think that's the deal here).

So the important game design considerations here are:

* how steep do you want the item progression to be?
* how long do you want the player to "work" for a given item?

**Flat or steep progression**

Do you want a flat progression where cheap items from the beginning of the game are still valuable in the late-game? Or do you want a steep progression where the player reaches whole new orders of magnitude of wealth opening up completely new tiers of items to them?

When you are going for the first, it's simple: Keep the reward constant throughout the game. This is, for example, done by the Zelda series where a rupee in the beginning is usually as easy to get as in the end.

When it is the latter extreme, you want to go for a polynomial (price * tier ^ x) or even exponential (price * x ^ tier) curve for both item prices and money rewards. That makes sure that when the player wants to make money to unlock tier 10 items in reasonable time they need to fight tier 10 enemies.

**Work factor**

That's a simple multiplier to both prices and rewards. When you want the player to kill 20 tier 10 enemies to afford a tier 10 sword, have the sword cost 20 times as much as the money reward for a tier 10 enemy.

By the way: The money progression in many RPGs is designed in a way that new item tiers are made available to the player *after* they acquired enough money to buy them. You usually find the ideal prices by calculating how much money the player should have gained through the expected amount of combat encounters when reaching a given shop and price the items it sells slightly below that amount of money.
> 5 votes

# Answer
As Philipp already wrote, there isn't one algorithm, but I think one could say there are a number of common algorithms with different characteristics, and you take advantage of those for different parts of game progression.

So if you want to ensure a player doesn't get an item too early, you make it dependent on a numeric (currency, in your example, but could also be a reputation, skillpoints level, xp points etc.) that they can only obtain at the desired point.

### How do I ensure a numeric is only obtained at the desired point?

By handing out that kind of numeric only at predetermined points, maybe even only once, e.g. whenever the player first finishes a given level or mission, give them 10 skill points. Replays can reward a little of that numeric (say, 1), so that a player who is stuck on one level can e.g. skip that and re-play a few other missions to make up for that.

If you don't have any predetermined points (e.g. because your game is a PvP shooter without levels or story mode, just repeated play of the same maps), you usually reward the numeric on other significant events (like enemy kills) and make it increase exponentially, and/or depending on player *and* enemy level, to make it impractical to grind for with low-tier enemies, and to reward a low-level player who manages to take down a higher-level enemy.

### How do I ensure a player advances only over a certain time?

Beyond that, you can select the powers, cool-downs and power levels of both opponents so the time taken for them equates to the amount of currency you want to dispense in a certain amount of time. E.g. in our shooter example, a player can only do a certain amount of damage in a certain time. You select their enemies' health levels so they can withstand that amount of damage for that long, then reward the desired amount of the numeric.

If that's not enough, you can always put an artificial cap on a numeric, like only awarding a certain amount within 24 hours, maybe hiding it behind a conversion (e.g. players earn iron ore, but the iron mongers take 1 day to process it into iron that you can actually give to the blacksmith to have your sword made).

### In the end, you want a single number

What this generally ends up as is you get a bunch of conversion rates, where it all boils down to a common base numeric in the end, which is what measures progression, or rewards, or whatever. Examples for numerics can be abstract things like experience points, or "junk" loot drops that translate to currency directly, but also very concrete things like "successful damage dealt" that can be used to allot different percentages of a killed enemy's loot when several players take down the same enemy.

### How do I make players get different gear for different purposes?

There can be separate groups of such base numerics. Often games work with one base numeric for common items, and different ones for endgame items. That way, you e.g. force players to actually play easy PvP content to unlock PvP gear needed for the harder PvP content.

So how do you make PvP gear different from PvE gear? Well, there are many ways. You could just make PvP reward armor/weapons that are so much stronger than PvE ones that you need them to avoid being taken out (works best if PvP is endgame-only). Some games have different "damage types" for different enemies. So PvP armor would just have a much higher resistance to PvE bullets than to PvP ones. This resistance could also take the shape of a buff that is simply applied to every player in PvE areas.

You can even monetize that, by e.g. making players have separate PvP and PvE armor, but offering armor that works in both places for money in your store. A good compromise between monetization and not making it unfair by offering something that couldn't be unlocked by playing. It's just a convenience (as long as a lower-level plater can't wear higher-level armor bought from the store until (s)he has leveled up).

### How do I prevent higher-level players from going after low-level enemies?

As to your example: If you want to reward/punish players for fighting higher/lower level enemies, you'd want to change `<player level> * <enemy level>` to something more like `min(<player level>,<enemy level>) * max(1,<enemy level> - <player level>)` (I'm making this up on the spot, fiddle with it). The first part ensures that a low player doesn't suddenly get rewarded as high as a higher one, but a high player fighting a low-level enemy only gets rewards at that low level. The second part means you get a bonus for fighting up, but you don't ever lose points when fighting down. Or, depending on your numbers, it might be a better idea to calculate a malus for fighting down, just ensuring a minimum reward is still given in such cases.
> 1 votes

---
Tags: rpg, mathematics
---


title: One large tileset or multiple tilesets

text:
# Question
Title: One large tileset or multiple tilesets
I'm currently writing a 2d tile scroller for a hobby project and I can't find any resources to give me a clear answer to which is more efficient to do.

Each block contains tiles 44 by 24, 32px x 32px in size, and I'm rendering all immediately-adjacent blocks offscreen. With each block, I am specifying what the types of the tiles are, such as Sand, Grass, Pavement, etc. My end goal is to have dozens of unique tiles in each set, potentially having several "Grass" sets to pull from, to have a diverse set of landscapes.

**What I want to do:**
I would like to only load tilesets that have tiles that appear in the loaded blocks. I would do this by marking tile "families" in Tiled, as well as giving them an ID that pertains to that tileset specifically.

However, I don't know if it's just better to load all of the tiles from one large tileset on the game's start and just keep it in memory, instead of making frequent content loads

**Will the game potentially run more efficiently dynamically loading tilesets based on need, or one very large tileset when the game first starts?**

# Answer
Is memory efficiency really a problem? 2D textures are not typically huge enough to cause issues. Splitting the tilesets into too many textures may even cause problems in itself, since switching textures is not always cheap on the GPU. You should probably just optimize for your development efficiency at this stage.

Unless you're intending to have loading screens, dynamic loading of a texture may result in a glitch. Typically you're not able to load content in the background, so loading a texture is a blocking operation. In some cases, the block may be long: for example, my HDD shuts itself down after some idle time and takes *seconds* to start up.

Additionally, `ContentManager` does not unload assets unless `Unload()` is called (unloading *everything*), so if you're using a single `ContentManager`, memory use will creep up anyways during gameplay.
> 1 votes

---
Tags: 2d, monogame, tilemap, memory-efficiency
---


title: Lost in Development

text:
# Question
Title: Lost in Development
My name is Julian Ngolla. I am a 20 year old biology major who is a junior at Hunter college in NYC. In other words i am constantly busy and am basically broke. Ever since i was a kid me and my brother have been die hard gamers and have loved every second of it. Over the past 5 or 6 years my brother and i have been seeing something wrong in the directions some Games are going like call of duty and battlefield. Games like these usually still end up being short term fun so it's not that big of a deal. Games like Destiny, The division, The Witcher, and ESO on the other hand, that promise long term value and rewards based on commitment, seem to not be living up to the grandeur we so fantasize. Don't get me wrong, i have played all of these games and bought all of their DLC along with reaching max level and/or top spots on their leaderboards, and i have Loved every minute of doing so. Unfortunately once i reach a certain point in a Game, where i can't go any higher, i start to fantasize of all the things that could have been. What if the Witcher had multiplayer, what if you could travel the stars seamlessly in Destiny, or enter every building NYC in the Division. What if ESO had hundreds more abilities, 10 more attributes and 50 more races allowing for endless build opportunities. Or my favorite what if any mmorpg these days incorporated Runescapes skill and grinding system. (Albion Online shows promise)

Games like overwatch and battlefield Will always be around and i can't wait for them to come out. They provide me with the short term fun and excitement that doesn't require much to be rewarded. But when it comes to my favorite games, the ones i have to put countless hours into to be rewarded, they don't seem to be doing the trick anymore.

Now the fun part. Do to my lack of drive and commitment to recent games, i have set out on a journey to make the best one ever. Over the past few months i have been brainstorming a game idea that would combine the most popular genres all into one. It's part Mmorpg, part Fps/Tps, and part Moba. My main inspiration Comes from Dota 2 and League of Legends, where either win or lose i would still be upset that my time with whatever character i was playing (Mostly shaco) has to come to an end. I mean, just imagine playing an rpg as Lissandra or Dragon Knight then switching over to pvp to kick some ass with them. Win or lose you can still go back to mmo mode and evolve and Progress as a character. Pretty sick right?!

So... As of now i have over 1000 pages of Lore, 1000 pages of character information containing the weapons and abilities of over 80 unique characters split into 4 warring factions, and I have the character models of each hero imprinted in my head. I have over 700 pages of gathering and crafting mechanics which includes a skilling system for both combat and non combat skills ( similar to runescape).

To some it all up, and dumb it all down, On a few thousand pieces of paper, i have created a game that is basically an mmorpg version of league of legends where you advance your character by leveling up a multitude of skills that define your role and play style.

So the main question i have for you all at the moment is... What Next?

# Answer
The next step would be to secure a budget of several million dollar to hire a team of a few hundred experienced people, because that's what it would take to create the greatest game ever. Do you have several million dollar laying around? Or do you know any publishers who would trust you with a million dollar budget because you have a solid track record of executing several large game development projects successfully? No? Well, then I guess your game idea is too big.

When you have no experience with game development and no budget to spend, then I would recommend you to start small. Very small. Pick a very tiny subset of your concepts, learn some game development tools, and try to turn it into reality.

See how it turns out, have people testplay it, discard what the testplayers don't like and build on what they like. When you have a prototype of a game, think about how to acquire funding for hiring people to help you develop on the idea and turn it into a product you can sell.

Your first marketable product will still just be a tiny glimpse of your huge pile of concepts and far, far away from being "the greatest game ever". But getting it to market will not just get you the funding you need for your next game, it will also give you the game development experience to tell which parts of your concepts will not work out in practice anyway.
> 9 votes

---
Tags: game-design, rpg, mmo, game-maker, game-industry
---


# Question
Title: How to make map generation with Perlin noise look more like an actual map
I have been following a guide on Perlin noise, but I can't post the link here because of my current reputation level. I will post code if needed.

When I get noise from this distribution, I tend to get a very large fraction of values near the 0.5 range and very few on the fringes. You can see this from a sample which I turned into a quick graphic in the image below. I scaled my noise function by the width of the screen and had it increment an array at `index = noise` by 1 every time it generated a noise value. As you can see, the distribution is hardly Normal, as the fringes just drop out entirely.

What is the best way to make this distribution wider towards the bottom, but not towards the top? I want most of the values to lie in a Gaussian distribution, but I can't just use a Gaussian distributed random number because I need values selected close to each other to be close to each other (Perlin noise).

How does this relate to games? I'm using the noise function to generate terrain and biome information. I have one noise array for elevation, one for temperature, and one for precipitation. I figured I could just overlay them and then determine the color of a square depending on a Whittaker plot, but with the current program, I end up only getting biomes in the midrange of the plot (Temperate forests), and I never get Tropical Rainforests or Taigas. Below are a few images of my generation:

(I need 10 reputation to post this many links and the zoomed out version shows the problem better)

And zoomed out:

Here is my code for coloration. eNoise is scaled to 0-100, mNoise is scaled to 0-400, and tNoise is scaled from -15-40:

```
if(eNoise[i][j] < 55f) { color = Color.blue; }
            else {
                if(tNoise[i][j] < -15f) { //Tundra
                    color = Color.blue.brighter();
                } else if(tNoise[i][j] < 12f) {
                    if(mNoise[i][j] < 20f) {
                        color = Color.orange; //ST Desert
                    } else if(mNoise[i][j] < 50f) {
                        color = Color.yellow; //TG and Des
                    } else {
                        color = Color.green.darker(0.5f); //Taiga
                    }
                } else if(tNoise[i][j] < 20f) {
                    if(mNoise[i][j] < 30f) {
                        color = Color.orange; //ST Desert
                    } else if(mNoise[i][j] < 110f) {
                        color = Color.yellow; //TG and Des
                    } else if(mNoise[i][j] < 220f) {
                        color = Color.green.darker(0.3f); //TD Forest
                    } else {
                        color = Color.green.darker(0.2f); //Temp RF
                    }
                } else {
                    if(mNoise[i][j] < 50f) {
                        color = Color.orange; //ST Desert
                    } else if(mNoise[i][j] < 110f) {
                        color = Color.green.brighter(0.2f); //Savanna
                    } else if(mNoise[i][j] < 250f) {
                        color = Color.green; //TS Forest
                    } else {
                        color = Color.green.brighter(0.5f); //Tro RF
                    }}}

```

# Answer
> 0 votes
I have fixed this problem through the following method.

First, while generating noise values, I kept track of the minimum and maximum values.

Second, when storing the noise values into my array, I normalized the data: (value - min)/(max - min). This way, all my values are between 0 and 1, but are better distributed. The equation maps the minimum value to (min - min)/(max - min) or 0, and maps the largest value to (max - min)/(max - min) or 1, and it scales all the values in between.

---
Tags: tilemap, maps, perlin-noise
---


# Question
Title: How can a player exist at a location that is not expressly defined?
How do video games like Minecraft know how to place characters on an infinitely complex plane? For example, the game knows the character's place up to 10 or more decimal places and can display them at that location, but it only stores the blocks on the integer values. Here are other ways that I have thought about on how to phrase this question, because I know that I'm not being very clear:

* How can a player exist at a non-integer location?
* How can a player exist at a location that is not expressly defined?
* How do non-existent coordinates contain players, even if they don't exist?
* How can a game depict a player on coordinates it has not expressly stored?

I understand that the coordinates can be simply saved as doubles, but in order to store all the coordinates that a player could exist on would create a simply enormous file.

# Answer
A player *can't* exist at a location that isn't defined, because computers are discrete things. Bits in any representation of a number (integer or floating point) are either set or they are not set and the pattern they create defines a particular number which we interpret as location.

That doesn't mean you can't have multiple coordinate systems though. Just because you might define blocks in a Minecraft-like world with integers (because they will always exist at integer positions and never anything in-between) doesn't mean you cannot use floating point coordinates for the player or other objects, which allow you to represent the fact that there might be two blocks at X 1 and X 2, but the player is currently halfway between them at X 1.5.

In such an interpretation, I suppose you could say that the player's position is not "expressly stored" or representable in the block coordinate system, but it's certainly defined and expressible in the player's coordinate system and it's trivial to convert between them. You tend to need to convert between them in cases like rendering, where you want to put them all in the same coordinate system. At that point it's simply a matter of choosing a common coordinate system with the appropriate granularity. Sure, most floats can't represent numbers like 0.00000000000000000000134 accurately, but that's probably not relevant for the scale of your game.

You may also find this question about representing positions in a large world relevant, because the it's also common to use hierarchical or chunk-based coordinates in these really large worlds. This helps you combat the precision and range issue that the inherently-finite nature of computers impart on your numbers. Using two coordinates ("chunk" coordinate, and local coordinate with that chunk) is similar to my first example; you can't necessarily represent all *values* in all coordinate systems *simultaneously*, but you can do local conversions where it matters. For example when rendering you generally only consider a certain fixed number of chunks visible around the player and can choose a coordinate system for rendering that makes it possible for you to map everything together with an appropriate resolution for the task of rendering.
> 2 votes

---
Tags: coordinates
---


title: Trying to make 3D game look like 2D

text:
# Question
Title: Trying to make 3D game look like 2D
I'm making a 2D dungeon crawler. The problem I found, it is that trying to animate the movement through the dungeon it is hard as hell. Then I thought that maybe a 3D dungeon will be better for this, but I don't like it. Are anyways to make a 3D game look like a 2D game? I mean...

There is some kind of shader o camera mode to achieve a 3D game look like this?

(Tough the game is in 3D, looks like it was a 2D game trying to be 3D).

# Answer
Use an orthographic camera instead of perspective camera.
> 1 votes

# Answer
I believe you should still want to use a perspective projection instead of orthogonal one, as there is still a perspective in it.

There's some ways on how to achive it. One would be using a perspective projection and tweak the fov to achieve the narrow camera effect and maybe a low resolution framebuffer (OpenGL) and resize it to get a pixelated effect. Second would be using a ray casting method which is used for some old 3D games.

There should be more ways to achieve this though.
> 1 votes

---
Tags: 2d, 3d
---


# Question
Title: How should I design game object dependencies between windowing, input and behavior systems?
This is my first time attempting to create a game engine. I came across a theoretical problem and would like to solve it before implementation. Right now I have a `WindowSystem`, which opens the window, sets the `GL_CONTEXT`, etc. I would like it to be responsible for all things window. Then I have another system that manages input called `InputSystem`. Then I have a `BehaviorSystem` for game object behavior.

The problem: Consider a game object representing a menu where it has options to change the resolution/other graphics settings. How can I link these three systems with minimal coupling so that a `Behavior` script can close the window? Normally systems interact through components, but there's no component for the window. From what I've read systems shouldn't know about each other. I haven't a clue how I could go about such a scenario.

# Answer
There's no one right answer for communication between different domains of any piece of software. In your case, it sounds like you want something like an "event" system. You should give your systems the ability to subscribe to events that other systems "raise" with information about the event. The Observer Pattern is a common pattern when implementing events.

For example, System A is interested in Event E from System B. You can pass System A an interface it can use to register a pointer to a function, say EventHandler(Event e), with System B, or it could register a callback interface or a delegate or other similar concept. System B maintains a list of these interfaces/functions and calls them with the event as an argument when it wants to raise the event.

You can also use a "central dispatch" type class that stands in between these two if you think the extra layer of indirection makes your architecture easier to maintain.
> 1 votes

---
Tags: architecture, entity-system
---


# Question
Title: Finding a point between 2 moving points colinearly , given 2 moving points and distance
P/S: The engine I work on doesn't have grouping integration. That's why I need a formula to change the position.

A------B---------------C

A and C are moving points that can move anywhere

A = (xa, ya), C = (xc, yc)

B (xb, yb) is a point between A and C colinearly

With one condition that distance of AB = constant = r, distance of AC can be varied.

How to find xb and yb?

**Asked from Mathematics StackExchange:**

> Deepak says:
>
> The locus of all possible points B is a circle centred on A and of radius r. The intersection between this circle and line AC will give you point B (and another point opposite it on the circle which you can neglect).
>
> Try to write down the relevant equations and solve them?

Example: http://www.mathopenref.com/collinear.html

# Answer
1. Calculate AC (xC \- xA, yC \- yA)
2. Normalize it
3. Multiply it by r
4. Add that vector to A : done !
> 1 votes

---
Tags: 2d
---


# Question
Title: How to follow a car with correct rotation
I am making a game where car will follow a user car. I am moving use car using keyboard keys it is working fine running on my game environment roads smoothly. To follow enemy car i am using nevMesh, it correctly following but the following car/enemey car rotation is not correct. I am surprise that how do i control it? or is there any other way to acheive this thing

# Answer
> 1 votes
Make the gameobject face towards is velocity vector (or its last non-zero velocity vector):

```
 float angle = Mathf.Atan2(rigidbody2D.velocity.y, rigidbody2D.velocity.x) * Mathf.Rad2Deg;
 transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.AngleAxis(angle, Vector3.forward), rotateSpeed * Time.deltaTime);

```

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


# Question
Title: Frameskipping in Android gameloop causing choppy sprites (Open GL ES 2.0)
I have written a simple 2d platform game for Android and am wondering how one deals with frame-skipping? Are there any alternatives? Let me explain further.

So, my game loop allows for the rendering to be skipped if game updates and rendering do not fit into my fixed time-slice (16.667ms). This allows my game to run at identically perceived speeds on different devices. And this works great, things do run at the same speed.

However, when the gameloop skips a render call for even one frame, the sprite glitches. And thinking about it, why wouldn't it? You're seeing a sprite move say, an average of 10 pixels every 1.6 seconds, then suddenly, there is a pause of 3.2ms, and the sprite then appears to jump 20 pixels. When this happens 3 or 4 times in close succession, the result is very ugly and not something I want in my game.

Therfore, my question is how does one deal with these 'pauses' and 'jumps' - I've read every article on game loops I can find (see below) and my loops are even based off of code from these articles. The articles specifically mention frame skipping but they don't make any reference to how to deal with visual glitches that result from it.

I've attempted various game-loops. My loop **must** have a mechanism in-place to allow rendering to be skipped to keep game-speed constant across multiple devices (or alternative, if one exists)

I've tried **interpolation** but this **doesn't** eliminate this specific problem (although it looks like it may mitigate the issue slightly as when it eventually draws the sprite it 'moves it back' between the old and current positions so the 'jump' isn't so big.

I've also tried a form of **extrapolation** which does seem to keep things smooth considerably, but I find it to be next to completely useless because it plays havoc with my collision detection (even when drawing with a 'display only' coordinate - see extrapolation-breaks-collision-detection)

I've tried a loop that uses **Thread.sleep** when drawing / updating completes with time left over, no frame skipping in this one, again fairly smooth, but runs differently on different devices so no good. And I've tried spawning my own, **third thread** for logic updates, but this, was extremely messy to deal with and the performance really wasn't good. (upon reading tons of forums, most people seem to agree a 2 thread loops ( so UI and GL threads) is safer / easier).

Now if I remove frame skipping, then all seems to run nice and smooth, with or without inter/extrapolation. However, this isn't an option because the game then runs at different speeds on different devices as it falls behind from not being able to render fast enough.

I'm running logic at 60 Ticks per second and rendering as fast as I can.

I've read, as far as I can see every article out there, I've tried the loops from My Secret Garden and Fix your timestep.

I've also read:

Against the grain

deWITTERS Game Loop

Plus various other articles on Game-loops. A lot of the others are derived from the above articles or just copied word for word.

These are all great, but they don't touch on the issues I'm experiencing. I really have tried everything I can think of over the course of a year to eliminate these glitches to no avail, so any and all help would be appreciated.

**A couple of examples of my game loops (Code follows):**

**From My Secret Room**

```
    public void onDrawFrame(GL10 gl) {

        //Rre-set loop back to 0 to start counting again
       loops=0;

       while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip) {
           SceneManager.getInstance().getCurrentScene().updateLogic();
           nextGameTick += skipTicks;
           timeCorrection += (1000d / ticksPerSecond) % 1;
           nextGameTick += timeCorrection;
           timeCorrection %= 1;
           loops++;
       }

       extrapolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks;
       render(extrapolation);
}

```

**And from Fix your timestep**

```
double t = 0.0;
double dt2 = 0.01;
double currentTime = System.currentTimeMillis()*0.001;
double accumulator = 0.0;
double newTime;
double frameTime;

@Override
public void onDrawFrame(GL10 gl) {

    newTime = System.currentTimeMillis()*0.001;
    frameTime = newTime - currentTime;
        if ( frameTime > (dt*5)) //Allow 5 'skips'
            frameTime = (dt*5);
    currentTime = newTime;

        accumulator += frameTime;

        while ( accumulator >= dt )
        {
            SceneManager.getInstance().getCurrentScene().updateLogic();
            previousState = currentState;
            accumulator -= dt;

        }

        interpolation = (float) (accumulator / dt);

        render(interpolation);
}

```

# Answer
From what I see, the game loops you are trying to use are somewhat specialized. I don't know why you chose those ones, but in my opinion you are trying to solve problems that don't exist in the first place.

Instead of copy-pasting a game loop from some site, I suggest you think about how your game is made and what your priorities are, and then create a game loop based on that.

In general terms, I like to visualize a game as composed of three elements:

* The **game state** is all the data in your game. Positions, angles, files and so on. No programs, just data.
* The **update logic** is a program that takes inputs (such as time, user input, network input and so on), and modifies the game state based on such inputs.
* The **display logic** is a program that takes a game state and *without modifying it*, displays it to the user.

If you can split your game into these three elements, then you're pretty much on the other side.

It is now depending on what does each one of those elements look like, and what your priorities are, to make a game loop that works for you. But first, the bad news:

The only way to guarantee that your game will run at a desired framerate all the time, is to make sure that:

* It takes much less to do an iteration of the update logic, than the time it is supposed to simulate (for example: simulating one second of game time takes much less than one second)

and

* The display logic takes much less than the framerate you want to display the game at.

If you can't make these guarantees, then you will have to make compromises.

A common idea in modern games is that it is more acceptable for the display logic to fall behind, than for the update logic to fall behind. That means that, if for example a frame takes longer to display than usual, the game state should still be running in real time, even if some frames are dropped.

A starting point for a game loop that does this could look like this (in pseudocode)

```
current_time = 0
previous_time = 0
game_logic_step = 1 / 100 -- doesn't really have to be the same as the drawing framerate

while running do
    current_time = time()

    while previous_time <= current_time 0 do
        update(game_logic_step) -- one step of update logic
        previous_time = previous_time + game_logic_step
    end
    display() -- display logic. As long as the game state doesn't get changed here, we're okay
end

```

With this, you're drawing as fast as you can, and you're making sure that the game state is always up to date.

This game loop is pretty robust, and is more than enough for 90% of the games I've ever worked on, and I am willing to guess that it will be more than enough for your game.

However, if showing all of the frames is more important than keeping the game state up to date (as in most older console games), then your game loop could look more like this:

```
current_time = 0
next_time = 0
draw_logic_step = 1 / 60

while running do
    while current_time <= next_time do
        wait_some_time()
        current_time = time()
    end
    next_time = current_time + draw_logic_step
    update(draw_logic_step)
    display()
end

```

Notice that we are fixing one `update()` call for each `draw()` call. With such a game loop, you will be showing all frames, while capping the frame rate. However, if one iteration of the loop takes more than `draw_logic_step`, then the game will slow down (but no frames will be dropped).

Those two game loops should suffice for the vast majority of games. Variations with interpolations, extrapolations, multiple threads and the like, are in my experience used only to optimize for corner cases where you want to push the update logic to the limit, yet keep the game running as smooth as possible.

Doing such optimizations though, is complex, and will make the game much more difficult to write and debug. In my opinion, you should start with a simple game loop as above, and you will see that it will work pretty well.

In fact, if your game is simple enough so both the update and display logics are really fast, then either of those two loops will work perfectly with no dropped frames or game slowdowns.

If your game is simple enough, and you are still dropping frames regardless of the game loop you use, then I would be inclined to think that the problem is not within the game loop but on your actual processing. What I would do is remove the fancy gameloop, use a simple one, and focus on understanding why are you skipping frames and fix that instead. Unfortunately, this changes the discussion from gameloops to how to debug and fix your code.

Some things that may help you are:

* On a comment, you mentioned that your update logic is taking 4ms. For 60fps, that is quite a lot, as it's about 1/4th of all the time you have for each frame. 4ms is not borderline high, but you may want to ask yourself why is it taking so much.
* You also mention vsync. In practical terms, Vsync means that your present call (probably `swapBuffers()`) will stall until it reaches a refresh point. I wouldn't worry about vsync too much, because:

+ If vsync is making your program stall for a whole frame, it is because you already missed the previous frame drawing deadline. Removing vsync won't solve this, and you still have to make your program run faster.
    + If your logic is slightly more than 1/60th of a second, vsync will manifest itself as a sudden framerate drop from exactly 60fps to exactly 30fps. That is not your case, so I wouldn't focus on vsync.
* Remember that your program is written in Java, which is a garbage collected interpreted language. Even if you do everything right, garbage collection cycles will stop your program completely for a very noticeable length of time, and you have no control over this. If you want to have more predictable performance, you should consider writing your game with the JNI in C. I've heard Xamarin.Android has better performance, if C# is your thing.
* But even so, remember that your program is running on a mobile processor in a multitasked environment. The OS will throttle the CPU, and will yield the CPU to other processes, meaning that the performance of your game is even less predictable. If you want complete predictability, write games for consoles instead.
* In the grand scale, I wouldn't worry too much about the problem you're facing. I would dedicate much more time to making sure the game is fun, because that's what really matters. I don't think that a fun game will stop being fun because of an occasional dropped frame. In fact, with so many things going on in the screen at the same time, I doubt people will even notice dropped frames, but that is just my humble opinion.
> 7 votes

# Answer
Some suggestions to consider:

1. Reduce your target frame-rate below 60: Some devices are just so poor in performance that you cannot expect 60fps. There are many examples of commercial games which run at or below 30 fps, and most people don't notice the difference. 60 is ideal, but you just can't expect many mobile devices to be able to handle 60fps for any serious game.
2. Code Optimizations: If there are things that you are doing every frame, which you could do less frequently, then you should consider having a secondary update function which occurs only every X frames. Look for bottlenecks. Do some benchmarking and determine what in your loop is taking the most time, and try to determine if there are faster algorithms for what you are doing. Try other algorithms and see if the benchmarks improve.
3. Reduce the game quality: Reduce the number of game objects; Do fewer draw calls; use faster shaders; Reduce shadow and lighting quality; Use lower polygons objects; etc. You could even allow the player to customize their own quality settings.
4. Release two different versions. A low-end version with 30fps and a high-end version with 60fps. Make it clear to the players that they are not the same. You could even consider removing features from the low-end version to make it even more obvious. ('Limited' and 'Full' versions.)
5. Don't support low-end devices: You just can't expect all devices to be able to handle 60fps. If you absolutely have to have 60fps, then drop support for any devices that cannot keep up. Try to optimize as much as you can and are willing to, but at some point you just have to say: "This device is not worth the effort to support it." The big game companies do this for good reasons!
> 0 votes

# Answer
I have a similar problem with jerky frames using android GL 2.0.

*When traced on android studio GL profiler I saw that the glcompileshader function is called multiple times during game play. This is an expensive call but **accounts for the jerkiness**.*

What causes these multiple calls to glcompilershader? I can only guess happens because the shader is invalid but I get no errors at creation. Not sure if accessing attributes in the shader causes a recompile of the shader. Still trying to debug this nightmare.
> 0 votes

---
Tags: sprites, movement, game-loop, interpolation, movement-prediction
---


# Question
Title: Calculating the angular momentum of rigidbody in Unity3D
Knowing that angular momentum in 3D is `L = Iω` (**moment of inertia** *times* **angular velocity**), how do I calculate it in video game world?

In I have the diagonal inertia tensor `rigidbody.inertiaTensor` and I know the angular velocity `rigidbody.angularVelocity` **am I correct when I calculate it like this?**

```
Vector3 angularMomentum = new Vector3(
    rigidbody.inertiaTensor.x * rigidbody.angularVelocity.x,
    rigidbody.inertiaTensor.y * rigidbody.angularVelocity.y,
    rigidbody.inertiaTensor.z * rigidbody.angularVelocity.z
);

```

Though, that leaves out the property `rigidbody.inertiaTensorRotation` which makes me think that this is not correct. What actually led me to the other question: In Unity3D, what is the relation between inertiaTensor and inertiaTensorRotation?

# Answer
> 1 votes
That's correct. In a few cases, you will want to take into account the `rigidbody.inertiaTensorRotation`. It defines the rotation of the moment of inertia. However, in most cases, this is just going to be the identity quaternion.

# Answer
> 1 votes
It seems to me that what you're doing has the correct basic form. But I think `rigidbody.inertiaTensorRotation` needs to be taken into account, though I'm not 100% positive on this either.

I would argue though, that it must be that `rigidbody.inertiaTensor` is diagonal with respect to some arbitrary coordinate frame, while `rigidbody.angularVelocity` is most likely computed with respect to the world axes. In this respect, simply multiplying the two wouldn't be correct. One would need to rotate either `rigidbody.inertiaTensor` or `rigidbody.angularVelocity` into a common frame first. Perhaps then, `rigidbody.inertiaTensorRotation` would take the inertia tensor into the world frame, thus allowing for multiplication with the angular velocity.

That's my thought at least. Does anyone know if my assumption about the angular velocity is correct?

# Answer
> 1 votes
I dug into this some more and have come to the following understanding. I'm open to be corrected though, so if anyone knows more, please chime in. For now though, this is what I think is going on.

`rigidbody.inertiaTensor` contains the diagonalized elements of the inertia tensor or the principle moments of inertia. These correspond to some internal symmetry of the rigid body and are expressed relative to some set of axes which need **not** be the same local axes used to describe the body. The `rigidbody.inertiaTensorRotation` gives you the rotation needed to express the inertia tensor with respect to the body’s local frame. `rigidbody.angularVelocity`, however, is expressed in world coordinates.

So, in the most general case, we need to apply two rotations to the diagonal inertia tensor in order to find the angular momentum via Unity’s angular velocity vector: `rigidbody.inertiaTensorRotaion` defines the rotation for the tensor into the body’s local frame, and `rigidbody.rotation` defines the rotation for that transformed tensor into the world’s frame.

The exact implementation of how to do this may get ugly. I wanted to work within the standard mathematical frame that I have learned: matrices for tensors and rotations as opposed to fiddling with Unity’s quaternions. I wrote up my own class to do this, although Unity has the Matrix4x4 class, which could work. But you’d have to be mindful when working with the extra dimension, as inertia tensors and rotations are most commonly written as 3x3 matrices. The relation between quaternions and rotations can be found readily.

Another note is that you need to make a similarity transformation (had a link to Wolfram Math World here, but apparently I don't have enough reputation point to include it) when rotating the inertia tensor. (I can't figure out writing in latex on this thing, so the following notation will be ugly) You want:

**I\_new** = **R\*I\_old\*RT**

where **I\_new** is your newly transformed matrix (inertia tensor), **R** is the rotation matrix corresponding to one of the quaternions, **RT** is the transposition of that matrix, and **I\_old** is the original inertia tensor that you're transforming.

I hope this can be of use. And again, if anyone knows this to be incorrect, please post and correct me.

---
Tags: unity, physics, rigid-body-dynamics
---


title: Does Unity let you code in Java?

text:
# Question
Title: Does Unity let you code in Java?
I am fairly new to Unity3D experience , but I have a very good knowledge of Java and Android development. I am really confused that if Java is at all needed for developing android applications? I read somewhere in Unity documentation that adding behaviour to objects in Unity requires use of scripts, and that unity only supports C# , .Net , and Boo scripts. Is there no use of Java at all?

# Answer
Java is not supported by Unity. You should check out C#, however; it's a very similar language that takes a lot of influence from Java while arguably smoothing out some of the rougher edges of the language. It should also be noted that you will need both Unity Pro and Unity Android Pro in order to create Android games using Unity. As jhocking and ashes999 note in the comments, you don't need Unity Pro and Unity Android Pro top release commercial Unity games on Android.
> 11 votes

# Answer
Unity supports only `C#`, `JavaScript` and `BooScript` for scripting. However as Philipp mentioned, if you know Java then you know 90% of C#. I still know only Java and C++ and its easier for me to translate my logic into C# (Given that I didn't know much about C# even after coding for a year in Unity).

You can however write plugins in Java for any native feature not provided by Unity or to implement some third party SDK such as ads made specifically for Android platform. Same is true for Objective-C for iOS platform.
> 4 votes

# Answer
Actually, you *can* use cross-compiled Java (i.e. Java source compiled to e.g. managed .NET code) with Unity3D - it has some caveats and problems, but it is definitely possible, at least on a proof-of-concept level; it also *doesn't* have to be done through the plugin system, as IKVM generates a managed code automagically, and managed libs can be attached directly:

http://answers.unity3d.com/questions/15308/can-i-access-java-code-from-unity.html

http://www.mono-project.com/docs/about-mono/languages/java/

so yeah, the other two answers are actually wrong.
> 3 votes

---
Tags: java, unity, unityscript
---


# Question
Title: Are there spritebatch drawing limitations on monogame?
I've reached a point that it seems when I draw too much on screen, monogame starts doing weird things.

When I call this code in the Draw method

```
public void drawDialogBox()
    {
        if (dialogueBoxOn == 1)
        {
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, null, Matrix.CreateScale(GameGlobals.zoom));
            spriteBatch.Draw(dialogBoxChara, new Vector2(89, 18), Color.White);
            spriteBatch.Draw(dialogBoxTexture, new Vector2(0, 108), Color.White);
            spriteBatch.DrawString(font, "àéùaDASASCZadhkjashdash", new Vector2(4, 108), Color.White);
            spriteBatch.End();
        }
    }

```

This happens:

This code is supposed to show the character, the textBox itself and the text. But the text isn't drawn correctly. If I comment one of the draw lines, it works.

Or this (if I only comment the character line)

Any ideas of what is happening here? I thought it was some SpriteBatch limitations, but I don't know...

EDIT: After following @Jon advice, i've reached this state

Now it shows the character and dialog properly, but the background and the walls are not displayed now. I have all the walls like this:

```
spriteBatch.Draw(leftcenterright4, new Vector2(0, 53), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0.5f);

```

And the background

```
spriteBatch.Draw(background, new Vector2(0, 0), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1f);

```

And the code from earlier fixed:

```
spriteBatch.Draw(dialogBoxChara, new Vector2(89, 18),null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0f);
spriteBatch.Draw(dialogBoxTexture, new Vector2(0, 108),null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0.1f);
spriteBatch.DrawString(font, "àéùaDASASCZadhkjashdash", new Vector2(4, 108), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0f);

```

# Answer
Use an override of the SpriteBatch.Draw() function in order to specify what layer you want to draw your sprites on. You are already specifying "FrontToBack" sort mode in your initialization so that is good.

Take a look here: https://msdn.microsoft.com/en-us/library/ff433988.aspx

More specifically, take a look at the "layerDepth" property. This is what you are looking for. Set this according to the order you want to draw your sprites on.

```
spriteBatch.Draw (texture, position, null, color, 0, Vector2.Zero, 1, SpriteEffects.None. 0.5f);

```
> 1 votes

---
Tags: c#, monogame, spritebatch
---


# Question
Title: Dropping through a platform in Clickteam Fusion 2.5
I am using Clickteam Multimedia Fusion 2.5. Currently, I have a rudimentary platformer game, with the following setup:

* player object is set as a **physics platform**, with the **physics engine** added to make it all work
* the floor is a **quick backdrop**, with the obstacle type of **obstacle**
* the only platform in the game is also a quick backdrop, with the obstacle type of **platform**

The way the game is setup, the player object can jump through the platform.

**WHAT I WOULD LIKE TO DO**

Is there a default, built-in way for the player object to be able to drop down through the platform? To be more specific, is there a default key press or a default combination of keys which would allow the player object to drop down through the platform?

I guess I could add it all in via the Event Editor, but I was wondering if there's a built-in way which handles it all.

# Answer
I have been unable to find a default way to achieve what I had in mind, so I ended up using a variant of what was explained in Sparckman's YouTube video, called **Indiana Jones - Falling Through Platforms - Tutorial**. I'm afraid that I had to delete the link, in order to be able to post a picture. See below.

The trick was to group the lines handling player collisions with platforms, and introduce switches and a counter. Whenever the player presses down arrow, the counter is set to 25, and the Collisions group gets deactivated. Immediately after that, the game starts reducing the counter down to zero. When the counter goes down to zero, the game checks if the Collisions group is deactivated. If it is, the game activates it.

The explanation is (I hope) clearer, once you take a look at the Event Editor:

Perhaps not the most elegant of ways to solve this issue, but it worked for me.
> 1 votes

---
Tags: physics, platform, clickteam-fusion
---


title: Load ads in splash screen?

text:
# Question
Title: Load ads in splash screen?
I have some ads that take a very long time to load. I was wondering it it is possible to have them load **while** the use was in the splash screen. I have looked at this answer:

https://stackoverflow.com/questions/5133342/how-can-i-make-my-ads-appear-faster-in-my-android-app

And the answer suggests to use a splash screen to load the ads. How can I figure out when the ads are loaded, to continue to my next activity? What will happen if the user is on airplane mode, will it get stuck in the splash screen? I have seen the admob add listener, but that needs the adview, but my adview is in the next activity? How should I tackle this problem?

Also, when I try to do this:

```
 AdView.setAdListener(new AdListener() {
     // Implement AdListener
 });

```

I get:

Non-static method cannot be referenced from a static context. The thing is, I am trying to see when the add **which is in the next activity** is done loading.

# Answer
> 1 votes
Your stack error comes from the fact that 'AdView' is a type, not an instance. For example, let's say you have the following class:

```
package simulator;

import java.awt.Color;

public class Dog {

public Color coatColor;
public static boolean mans_best_friend;

}

```

because all dogs are man's best friend, the statement

```
Dog.mans_best_friend = true;

```

is a valid statement, because the static modifier lets you use the type to set a variable. Likewise, you cannot have the statement

```
Dog.coatColor = Color.BROWN;

```

because 'Dog' doesn't refer to a specific dog object.

-

This means that you have to get a

```
new AdView();

```

Object somehow. If you read up on the documentation, there are usually 2 common ways to get the object.

1) a constructor: this is a simple allocation of new memory on the computer in order to hold all the variables it contains, usually fast, but inefficient to do multiple times. it gives you a fresh object

2) a GetInstance() method: It's more of a workaround that a method, it allows for one object to be created and allows for maximum efficiency of code, with absolute minimum customization.

Best of luck in finding a way to get your AdView Object!

---
Tags: java, android, software-engineering, monetization, advertisements
---


# Question
Title: Libgdx, TweenEngine - continous rotation animation without stopping/delay
I have a probably dumb question.

I'm trying to create a LoadingCircle so I just picked one image (you can see in the attachment) and made some sequences to rotate it:

```
 Tween.to(loadingCircle, SpriteAccessor.ANGLE, 1f).targetRelative(25).repeatYoyo(Tween.INFINITY,0).start(tweenManager);

```

And SpriteAccessor:

```
case ANGLE:
   returnValues[0] = target.getRotation();

case ANGLE:
    target.setRotation(newValues[0]);

```

It rotates of course, but 'to()' method gets the 'time' parameter. Now, the animation rotates the image, but slows down and stops rotating after the given time and starts from the beginning - speeds up and again - slows down.

Is it possible somehow to set the rotation to be continous, that it won't slow down and repeat the action? It's caused by the interpolation I think.

If you could point me the way I would be grateful!

# Answer
How about changing your approach to the simpler solution? You could just manually rotate the sprite in your update-method with something like the following: `sprite.setRotation((sprite.getRotation() + rotationSpeed) % 360);`. That way the sprite will smoothly spin around forever, and your code stays clean and straight-forward.
> 1 votes

---
Tags: java, libgdx, tweening
---


# Question
Title: What would be an efficient way to check if there is a collision in a 2d game?
As part of my final project of Algorithms and Data Structures, we have to develop an open world game in C++. I already got developed most of the game, but I haven't coded the collisions with the enemies.

First, I'll explain how the game works. It's an open world game, where there are 10 regions. The world is a big map, where only a small portion of it has to be visualized in the screen . The world is 40 screens x 40 screens, where each screen is 1900 x 1080 pixels.

In this world, there are 250 000 enemies that are distributed in all the regions, so that each region has 25 000 enemies.

Besides, there is a main character that has to travel around this world doing missions, collecting items and killing enemies.

Now, my problems raises here, what is the most efficiency way to check if the main character collides with any enemy, so that when he attacks this enemy and kill him I can eliminate the enemy from the world?

In order to solve this problem, I assigned each region a list of enemies, so that the amount of enemies to validates reduces significantly. I also have a function that returns the region where the main character is.

Then, to check for collisions I do this:

```
for ( Number of Enemies in the Region)

  if ( MainCharacter is colliding with an Enemy and MainCharacter kills the Enemy)
     delete Enemy from the Region

```

I think this way is pretty inefficient since I have to validate all the enemies in the region and I just want to validate the enemies that are closer to the main character or are visible in the screen.

How should I improve the collision detection so that it's more efficient?

I hope I made my self clear and I would really appreciate any help you can provide.

# Answer
The simplest way I could think of is to use a grid (2D if your enemies can only move on the xz plane and 3D if they can move up and down too). You will have to hold an additional reference to the grid cell inside your enemy objects, and also in the player object. This way, you will still have to iterate over all enemies in your map, but only check collisions for those that have the same grid reference as the player.

You will have to update the grid reference based on the object's position inside your update function.

Also, watch our for edge cases such as an enemy being in more than one grid cell.
> 1 votes

# Answer
I'm not entirely sure why you're checking each enemy for collisions if you're only worried about collisions with the player. If the player can only ever collide with enemies, then if you only check the player for collisions with enemies rather than all the enemies for collisions with the player, you would go from 25,000 enemies x 60fps = 1,500,000 checks per second down to 1 player x 60fps = 60 checks per second. Literally just:

```
void CheckForKills()
{
    if(MainCharacter is colliding with something)
    {
        Enemy enemy = something;
        if(enemy.isDead)
        {
            delete Enemy from Region;
        }
    }
}

```

No loop required. Having said that, I think that the absolute best way is to use something like a delegate. If you look at an established Game Engine like Unity, it uses an event to detect when a collision occurs and upon that collision invokes a method called OnCollisionEnter(). Then, in theory, you would go from 1,500,000 checks per second down to "only when a collision actually happens".
> 0 votes

# Answer
First thing to consider: You have your giant world broken up into manageable regions. So why not break up a region into more manageable pieces, like sub-regions? By doing this you can further break-down the total # of objects to check for collision detection. But this is just a side note.

Now, here is where you can achieve very quick collision checking for your game...

Assumption: A region within your game is composed of tiles. If so, what if a tile object has information about the enemies on it?

Now, the moment the main player enters any tile, you can quickly (and cheaply) know what enemies you are potentially colliding with (a tile object can have a list of enemies that are in it). Or, alternatively, you can have a mapping table that says "this Tile has these enemies in it".

So ultimately, based on the user's (x, y) location on the map, you can instantly know (i.e. in 1 single step) the tile object you are in AND quickly know the # of enemies to do further/deeper collision detection on (likely a small list of enemies).

The only thing to consider now is that you have to update a tile's enemy list based on every enemy running around the map (but that should be very cheap as well). It's all about the references.

*** Updated *** After reading from Deno's answer, I believe my approach is similar in style. But what I am suggesting in my answer is that you can totally avoid any kind of checking within a loop. Because basically you know the tile that you are in, and each tile knows what enemies are in it.

Pseudo-code below:

1. get tile T that the main player is in.
2. check if tile T has any enemies from its enemy list (or based on a mapping/lookup table).
3. do whatever collision detection you want.
> 0 votes

---
Tags: collision-detection, efficiency
---