# Question
Title: Lamba expressions: The => Operator. Any plain English help to understand this please?
I've been adding Google Play support into my game. For the most part I'm getting on swimmingly, but I'm having a hell of a time understanding exactly how the submission calls to submit score and achievements work.

It's the `=>` operator and surrounding method that confuse me, such as this one that I have in my code. It all works, I just don't know how. I've read up a bit and I think these are called Lambda expressions.

But I want to know *why* it is this way, and why it isn't made so we can just use the standard typical `bool` instead of making this strange way to send the result of whether or not our player is logged in.

Hope that makes sense. Here's the code in question:

```
Social.localUser.Authenticate((bool success) => {
        if (success)
            {
                Debug.Log("score authenticed successfully");
            }
            else
            {
                Debug.Log("score not authenticed, check user is signed in");
            }
     });
    Social.ReportScore(score, GPGSIds.leaderboard_pinball_wizards, (bool success) => {});

```

Particularly, the bottom line really has me stuck.

# Answer
> 10 votes
In this particular case, lambda expressions are used to handle the result of your `Authenticate` and `ReportScore` calls. Both of these calls are asynchronous, meaning they will be processed in the background while your game continues to run. Internally these calls will have to communicate with Google over the network which will take a while. It may be dozens of frames between the time you are making the calls and the time you are receiving the results.

See this example:

```
Debug.Log("Frame " + Time.frameCount + " - Sending authentication request.");
Social.localUser.Authenticate((bool success) =>
{
    Debug.Log("Frame " + Time.frameCount + " - Received authentication result. success=" + success);
});

```

Once you execute this, you will see that the call to `Authenticate`, and the execution of your lambda expression happen at entirely different times.

So how does this work? The signature of `Authenticate` is

```
public void Authenticate(Action<bool> callback);

```

so this method does not immediately return a result, because it simply is unable to immediately tell whether the authentication will succeed (because it has to wait for network communication to complete). So how can it tell you about the result once it is known? By allowing you to pass in a callback handler. `Authenticate` will call that callback handler as soon as it knows the result. That handler is passed in as the first parameter: `Action<bool> callback`, meaning, any method that can be called with a single boolean parameter and that does not return a result (=void).

So both these calls will be correct:

```
void Start()
{
    Social.localUser.Authenticate((bool success) => { Debug.Log("" + success); });
    Social.localUser.Authenticate(AuthenticationCallback);
}

void AuthenticationCallback(bool success)
{
    Debug.Log("" + success);
}

```

# Answer
> 14 votes
You are correct, these are lambdas. A lambda is basically a nameless function that you can write (almost) anywhere. It looks like this, in code

```
(parameters here) => { body of function here }

```

where "parameters here" are a list of parameters to the function as you would write parameters to any function definition, and similar for "body of function." The `=>` token is devoid of any other meaning except indication that the whole expression is a lambda. In particular is has nothing to do with equality or greater-than, in this context. It just as easily could have been some other arbitrary token, the language designers simply chose that one.

The alternative to passing a lambda is usually not a fixed value (that's why you can't just "pass a bool" instead. Lambdas are *functions*, so if you aren't passing a lambda you're instead passing a delegate (or the name of a function). That function needs to exist elsewhere.

Lambdas are useful for a variety of things, such as for specifying execution logic in a place that is nearby the surround logic that will use it. One often sees them employed as sorting predicates to a list, or as callbacks for asynchronous operations (which is what your use appears to be, on the surface).

Lambdas also have this neat ability to *capture* local variables, which means they can use those locals inside their bodies. This is useful because if a sort predicate requires a function taking two objects to compare against, that's all well and good: you could write a lambda or just supply the name of a `SortObjectsByWhatever` function you've written elsewhere. But if you want to *also* employ some other bit of runtime data in the body of that sort, it's often easier to do that using a lambda, because you can't always change the signature of the delegate type the sort function expects.

The MSDN has a comprehensive write-up on lambdas in C#.

# Answer
> 3 votes
In terms of general use, a Lambda is just an anonymous function. The main advantage is that they're easy to make anonymous / pass around to other frameworks or API's.

They generally consist of three parts:

1. arguments, usually wrapped in a parenthesis (not always),
2. =\> Lets you know that this IS a lambda not just an expression
3. a scope. Much like an if statement / loop you can follow it with a single line, or wrap you function in a scope using {}

take this function:

```
void foo(int bar){Debug.Log(bar);}
//called as
foo(5); //Outputs 5;

```

as a lambda it would looks like this:

```
var foo = (int bar) => {Debug.Log(bar);}
//called as foo(5); //Outputs 5

```

---

**Other uses:** As Josh Petrie mentioned in his answer, lambdas are very good at capturing local data.

This makes them very useful for tasks like threading. Rather than packing all your relevant data into an args struct, you can just use the vars straight into the function.

As you've seen already, they're also widely used as callbacks. Lambdas provide a clean and simple way for developers to leverage the power of a framework without needing to drastically refactor their own code.

---

Now, to use a Lambda in your situation is as simple as adding code to included scope

```
void customHandler(bool success){//insert code here}
//sends the lambda through the callback.
Social.ReportScore(score, GPGSIds.leaderboard_pinball_wizards, (bool success) => {customHandler(success);});

```

# Answer
> 3 votes
**What is Lambda?**

You can think of a lambda expression as just shorthand for an anonymous function:

```
void myFunction(bool value) {
    Console.WriteLine("my function({0})", value);;
}

// Action<bool> is the type of a function that accepts a bool parameter and returns void
Action<bool> f;
f = myFunction;
f(true);
f = (bool value) => {
    Console.WriteLine("my lambda({0})", value);;
};
f(true);

```

Result:

```
my function(True)
my lambda(True)

```

**Why do functions take lambda parameters?**

Welcome to the world of first-class functions! Being able to pass around functions in your variables opens up many possibilities. In this particular case, it is one pattern for writing nonblocking request-response code. This way, your game code doesn't just pause while waiting for the network request to finish. In essense, you tell the library "go run this request on the Internet, and take your time -- when you're done, do (this thing) with the response". that `(this thing)` part is the lambda you provide it.

For example, if I had a service SDK that exposed my functions this way, and you wrote the following code,

```
Console.WriteLine("1");
myService.Send(parameter, (string result) => Console.WriteLine("3. {0}", result));
Console.WriteLine("2");

```

You could conceivably get this order of output, where my server took 3 seconds to respond but your game didn't have to pause for 3 seconds while it was waiting for a response like it would have to if it was written synchronously

```
1:00:00.000 PM: "1"
1:00:00.001 PM: "2"
1:00:03.000 PM: "3. response from server"

```

**Other ways of asynchronicity**

In .NET, there are other async patterns, like async/await, or event callbacks for writing asychronous code. In some platforms (like \[earlier\] javascript+node.js), the lambda-based approach is the only option)

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


# Question
Title: Hexagon grid gets cut off when generated outside of the JFrame
I'm programming a hex-grid based game where you click on adjacent tiles to the player and when the player moves the map/grid moves in the opposite direction (using setLocation() on the jpanel inside the main jframe) so that, relative to the screen, the player is still centered.

When I pass in a big enough number of hexagons some of the grid generates outside of the jframe. When this happens, I can still make the player move around and open the menu and change player skins, but when moving north on the grid (when the top of the grid is what got generated outside the jframe) the grid just gets cut off and ends before the whole hexagon gets repainted.

I was wondering if there was a way to fix this that maybe I've simply just overlooked. My first thought was to delete and then regenerate the grid with new x,y coordinates each time the player moves and not use setLocation() at all, but I feel like that would be very inefficient and more of a brute force solution (last resort). I just feel like there has to be a more elegant or efficient way. I've tried using setSize(), setMinimumSize(), and setPreferredSize() methods to try and make the jpanel or the jframe's content pane bigger.

Picture to help:

# Answer
> 3 votes
You definitely should not be moving the JPanel around inside the JFrame, because the JPanel is essentially your work area, and since your work area is always a specific size, if you move it, part of it is going to be outside the JFrame, and part of the JFrame is going to be empty.

That being said, you must be redrawing the tiles every frame if you're able to move the character and use the ui, etc. Simply moving the x, y coordinates won't slow that process down at all. You mentioned that some of the hexagons were getting rendered outside of the JFrame, so you could implement a check that only renders the tiles on the actual screen.

Alternatively, if the map never changes, you could render the entire map to an image (or several chunks), and then each frame just draw that image in its appropriate location. I don't think this would save you that much time, but you could look into it.

---
Tags: java
---


title: Observer pattern payloads

text:
# Question
Title: Observer pattern payloads
Does anyone know what Nystrom meant in this excerpt from http://gameprogrammingpatterns.com/observer.html?

I created an example implementation of the observer pattern in c++ from my medal system.

I am wanting to pass my `KillType` enum to `onNotify` without muddling up the base Observer/Subject classes with that level of specifics.

My `Medals` class needs to know specifics about what type of kill it was so it can award the appropriate medal (ex. Headshot).

Does anyone know of a way to use templates to do this? Or what is a good way to get that level of detail from PlayerState to Medals?

The first thing I thought of was to use polymorphism and an Event class with a bunch of subclasses for each type. But that seems really class heavy to me to just pass some variables around.

Runnable Example

# Answer
> 3 votes
It makes sense to have your basic Observer and Subject implementations unaware of higher level data types, but at some point they have to commit to a common contract to be able to communicate.

You may just have a void\* to pass event data which the observer has to cast based on the type of event, but I prefer to be explicit about my types.

It's years since I've done C/C++ but I've played with your code and this is what I've come up with:

* I've made templates from your Observer and Subject base implementations, for which you need to specify the data types of the event and the event data, like `template<class EventType, class DataType> class Observer`
* I changed Medals and PlayerState so that they specify the event types of their base classes to be of type `Event` and the event data type to be of new type `EventData`, like `class Medals : public Observer<Event, const EventData &>`
* `EventData` holds any data that `Event`-handlers might require, like the type of kill made, or current ingame time or whatever.

This way the base implementations are unaware of specific data types, while your concrete implementations are type safe and have a common contract, specifically: "Observers of `PlayerState` will be notified with two parameters of type `Event` and `const EventData &`".

See https://wandbox.org/permlink/XLBXE0qNGqZScZwu for the final implementation.

---
Tags: c++, design-patterns
---


# Question
Title: What would be the easiest way to define actions of multiple buttons
So I'm creating a game that involves lots of different areas that involve pushing buttons to do certain things. Anyway, I'm trying to figure out how to let each button do its own separate thing, like open a door or things like that. I already know how to setup a Raycast between the player's mouse to the button, but now I'm just figuring out how to make each button trigger a separate action. Basically, should I set up a new tag for each button? Or create different scripts, even? I haven't tried anything yet and I need help. Thanks :D

# Answer
In unity you can work with UnityEvents. If all of your objects have a single action and two states ( on and off ) you can use two UnityEvents (ie OnButtonPressed or OnButtonEnbaled and OnButtonDisabled) for one script and populate the listeners in the inspector.

This way you can individually setup what functions on what objects must be called. When you press the button you fire the event withing the script. The UnityEvent then calls all the listeners you have set in the inspector or trough script.

Edit: Here I made a script called EventTrigger which can take any object and then call any of their public functions. In this case my target is a game object on which I'm calling the SetActive function.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EventTrigger : MonoBehaviour {

    public UnityEvent OnActivate;
    public UnityEvent OnDeactivate;

    public void TriggerOn(){
        if(OnActivate != null)
        OnActivate.Invoke();
    }

   public void TriggerOff(){
       if(OnDeactivate != null)
       OnDeactivate.Invoke();
   }
}

```

Then just call TriggerOn or TriggerOff whenever you have to.

How you connect all the components is up to you. One way would be to request the compontent from the interested object. The EventTrigger works for all gameobjects. Naming is generic so it shouldn't cause any confusion.

Keep in mind that it can only take functions with 0 or 1 parameter. Getter/Setters are also accepted.
> 1 votes

---
Tags: unity
---


# Question
Title: 2D Platformer Collision Detection Issues - XNA
I am developing a basic 2D platformer game to learn the basics of making a game engine and XNA. I have a CollisionHandler class that deals with AABB collisions between the player and the tiles of the map. The player on screen can collide with the tiles but it jitters when there is gravity (the character drops through the number of pixels that is the gravity vector). After dropping through those pixels when the frame refreshes he bounces back to above the block and then drops through again, as though the drawing happens before the position of the player is adjusted after the collision detection. I've narrowed it down to this possibility because without gravity, and while moving left to right, the player stops at a block (collides) but moves through the block at a distance which is the number of pixels that is the velocity while the move key is being pressed and when this key is released he 'snaps' back to where he should be.

This is the Update() function in the main Game class. I've tried different orders of updating the player and the CollisionHandler to no avail.

```
 protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        player.Update();
        collisionHandler.Update();
        base.Update(gameTime);
    }

```

This is the main part that I am struggling with in the Player class. I've also found that if the player is sliding without a key being pressed (there is no deceleration after a button press for now) he stops right on the dot at a block. Right now I've experimented with just collisions on the left side of the player while I sort this issue out.

```
        public void Update()
    {
        Input();
        Velocity += Gravity;
        Pos = new Vector2(Pos.X + Velocity.X, Pos.Y + Velocity.Y);
        rectangle = new Rectangle(Pos.X, Pos.Y, texture.Width, texture.Height);

    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, rectangle, Color.White);
    }

    public void Input()
    {
        if (Keyboard.GetState().IsKeyDown(Keys.D))
            Velocity = new Vector2(5, 0);
        else if (Keyboard.GetState().IsKeyDown(Keys.A))
            Velocity = new Vector2(-5, 0);
    }

    public void Collide(Rectangle r2)
    {
        this.Pos = this.Pos + GetLeftCollisionOverlap(r2);
        Velocity = new Vector2(0, 0);
    }

    public Vector2 GetLeftCollisionOverlap(Rectangle r2)
    {
        Rectangle r1 = this.rectangle;
        if (r1.Left < r2.Right)
            return new Vector2(r2.Right - r1.Left, 0);
        else
            return new Vector2(0, 0);
    }

```

This is the Handler that I am working with to detect collisions.

```
public class CollisionHandler
{
    private List<CollisionTile> tiles;
    private Player player;

    public CollisionHandler(List<CollisionTile> tiles, Player player)
    {
        this.tiles = tiles;
        this.player = player;
    }

    public void Update()
    {
        foreach(CollisionTile tile in tiles)
        {
            if(IsColliding(player.rectangle, tile.Rect))
            {
                player.Collide(tile.Rect);
            }
        }
    }

    public bool IsColliding(Rectangle r1, Rectangle r2)
    {
        if (!(r1.Right < r2.Left ||
             r1.Left > r2.Right ||
             r1.Top > r2.Bottom ||
             r1.Bottom < r2.Top))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

```

Some ideas that I've had to solve this problem are getting collisions before they happen, like a WillCollide method of some sort that prevents movement if there is a collision that will happen in the next frame. The only problem that I've had with this is that the way that the classes are structured I can't get the tile rectangles in the player class, and I'd prefer if the references for tiles and players are in the collision handler only, and leave it the way it is so that the player doesn't 'know' about the existence of any other classes.

Let me know what you think about this problem. I've done quite a bit of searching and haven't found anything that has worked for me.

Thanks - Alex

# Answer
I found the problem with this code. In the Player.Collide() I was updating the Pos of the player but not the rectangle/bounding box of this player. When I changed this the code worked as planned!
> 1 votes

---
Tags: c#, xna, monogame
---


# Question
Title: LibGDX - On the "slowness" of loading assets
Many tutorials I've seen put the loading of assets via AssetManager in a dedicated screen which displays some progress bar or image while the loading happens in background. Each "real" screen then gets the resources it needs from the asset manager, typically in the constructor, eg

```
public class GameScreen extends ScreenAdapter {

  private MyGame game;

  private Texture t1;
  private Sound s1;

  public GameScreen(MyGame game) {
    this.game = game;

    AssetManager am = game.getAssetManager();

    t1 = am.get("....", Texture.class);
    s1 = am.get("....", Sound.class);
  }
  // use t1 and s1

```

Now another source I've seen takes this concept a bit further and also does the actual get()s in the asset loading class, so screens don't have to do them themselves, eg

```
// in the Loader class

public AssetManager am = new AssetManager();
public Texture t1;
public Sound s1;

...
am.load(...);
am.load(...);
am.load(...);

// finishLoading() or update()....
...
t1 = am.get(...);
s1 = am.get(...);
...

// in the screen class

t1 = game.am.t1;
s1 = game.am.s1;
...
// use t1 and s1

```

Now my question is: is this good practice? What's the expensive part of loading assets, the AssetManager's `.load()`s or also the `.get()`s? (I thought it was only the `.load()`s.) Is removing the `get()`s from the screens really a performance gain?

# Answer
> 0 votes
Removing the `get`s from the individual screens is often done so that if multiple screens use the same resource they don't all have to qualify them by a name, instead they're fields on the asset manager.

This is done not for performance but ease of access and making sure each asset resource name is only referenced once.

So for two separate screens that are both using the same texture the code will be

```
public class ScreenA {
   ...
   public void render() {
      game.assetManager.someTexture.draw(...);
   }
}

public class ScreenB {
   ...
   public void render() {
      game.assetManager.someTexture.draw(...);
   }
}

```

instead of

```
public class ScreenA {
   private final Texture texture;

   public ScreenA(...) {
     texture = game.assetManager.get(Gdx.files.internal("graphics/sometexture.png"));
   }

   public void render() {
      texture.draw(...);
   }
}

public class ScreenB {
   private final Texture texture;

   public ScreenB(...) {
     texture = game.assetManager.get(Gdx.files.internal("graphics/sometexture.png"));
   }

   public void render() {
      texture.draw(...);
   }
}

```

The first way allows for the actual file-name of the resource to be the concern of the `AssetManager` and no other. It makes it easier to manager and allows for convenient refactoring.

# Answer
> 0 votes
The AssetManager's load method only adds the items to the queue of items to be loaded by the AssetManager. The actual loading is done in the finishLoading() (blocking) or update()(non blocking) methods. The get method only returns an already loaded item.

So the most expensive method is the finishLoading method as this will only return once all items are loaded. Usually in a loading screen the update() method will called during in the render method as it returns a value to show how much loading is done which can then be used to show loading progress on screen.

I don't believe there will be much, if any performance gains from calling get in the loading class compared to the screen class as get in either class is just retrieving an already loaded asset.

---
Tags: libgdx, asset-management
---


title: Problem with arrays (Error: SIGSEGV)

text:
# Question
Title: Problem with arrays (Error: SIGSEGV)
i am building a game with 100 levels and these levels are creatable by me and by the player with the level editor. For example there are some spikes and all their details are in a array of spike\_struct.. (i hope you mean how i organize it) I just want to save the data to a file so

```
ofstream ofs("data.dat", ios::binary);
ofs.write((char*)&data, sizeof(data));

```

*data* is a struct containing

```
struct datastruct
{
    int spikes[100];
    // number of spikes in 100 levels
    int blocks[100];
    // number of blocks in 100 levels
    spike_struct spike[100][1000];
    //Data of spikes (1000 is the max of spikes in a level and 100 is the max number of levels
    block_struct block[100][1000];
    //same as above
}

```

This causes an error: SIGSEGV, Segmentation Fault. I got this in debug mode.

How can i avoid this?

# Answer
I'm not sure but I would say that the SegFault is caused by the fact that you're not declaring your 2D array right at the start.

```
int spikes[100];

// Should be
int spikes[100][1000];

```

And the same for your blocks array.

For the moment, with:

```
spike_struct spike[100][1000];

```

You're trying to access at: spike\[100\]\[1000\] that don't exists yet
> 1 votes

---
Tags: c++, sdl2
---


# Question
Title: How to fold a view from 2 3D cameras in Unity?
I need to combine view from 2 or more 3D static cameras. Let's say I have 3 humans standing in line side by side.

* The first camera is viewing the left person and the left half of the middle person.
* The second camera is viewing the person on the right and the right half of the middle person.

Now I need to see the whole middle person.

Any ideas how I can do this?

I don't need to see code or some finished implementation, I just need some ideas, because I can not find anything on this.

# Answer
> 2 votes
You could create two cameras and create a split-screen-like view:

Left camera has a `ViewportRect Width` of `0.5` and the right camera has a `ViewportRect Width` of `0.5` and `X` of `0.5`. Now they are both visible on the screen.

Depending on what type of camera you are using, you may want to set the cameras next to each other so they have aligned boundaries or overlaps (I don't know completely what you want). But I guess this is a good start.

---
Tags: unity, 3d, camera
---


# Question
Title: Can I make the project files/source code of my comerical Unity game avalible as a DLC or with the game?
Is it legal and/or a good idea to let the players download the source code/project files of a comerical Unity game with the game or as a DLC?

# Answer
Before you publish your sourcecode, make sure you actually have all the rights to it. Be careful about any 3rd party assets you downloaded from the Unity marketplace or elsewhere which might end up in your project. You can only publish those with the explicit permission of the creator. This also applies to stuff you got for free.

Is it a good idea?

The game sourcecode will be quite useless for most of your target demographic. Most gamers will either not be able to read the code or won't be interested in it (I would certainly not look at it - that would just be detrimental to my game experience). But there are two small sub-cultures in every game community which will have quite a lot of interest in it:

* Powergamers who want to completely understand all the game mechanics. But not all of them will need the sourcecode to do that. A few will buy the source and then create a wiki which describes all the formulas and algorithms.
* Modders, because having the sourcecode allows them to change your game in any way they want.

The second demographic is the one you might want to cater to. An active modding community can add huge value to a game.

Just make sure they don't take your base-game and offer it for free to people who haven't bought it. Any OSI-approved open source licenses explicitly allow that, so they might not be the best to protect your business interests. You might want to ask a lawyer specialized in software copyright to draft a license agreement for your sourcecode which makes sure people can use it only for documenting and modding your game.

One downside of having a strong modding community is that any DLC you release later will compete with the content offered by the modding community, so it will only sell well if you can offer a level of quality which goes far beyond what the modders are able to deliver.
> 2 votes

---
Tags: unity, legal, marketing, open-source
---


# Question
Title: Adding Google IAP License Key into Unity Games
I have added Google Play Services and AdMob successfully into my app. But I want an in-app purchase button that lets you remove the adverts. (I have the button already but not the billing).

Google Developers Console tells me I need to input my app's specific license key into my app. The Android Manifest.xml to be specific. But it's not the clearest instructions. The Unity guide seems very lacking too, and mostly I can only find stuff about Unity IAP.

The Unity guide I did find tells me it makes the Manifest automatically and only tells me that I can write my own complete Manifest and import it over the top of the auto-made one.

I don't really want to do that if possible as I have just finished adding all the other Google stuff via Unity into the Manifest.xml

I'm sure this is a common feature that lots of devs use, so that makes me think there must be some way to do it via Unity.

# Answer
OK my confusion is solved. Basically I was confused thinking Unity IAP was not the same as Google IAP. In fact, it is, Unity is compatible with Google IAP and many others. So I had to go to Services and enable the IAP to authorize billing on my app.

I also had to retrieve the AndroidManifest.xml from my projects folder (Temp/StagingArea/), edit it in notepad to include the BILLING\_PERMISSIONS request, and the save my new Manifest into my project folder (Assets/Plugins/Android), this solved the Billing permissions issue i had
> 1 votes

---
Tags: unity, android, google-play-services, in-app-purchase
---


title: Separating Assets in Unity

text:
# Question
Title: Separating Assets in Unity
Well, my question in rather simple - or so I hope. What I would like to do is separate my game assets in the Unity game engine into separate files for the build. This way not all the assets are in one large file, therefore making for easier and faster updates (don't have to re-download one large file if there's only a small change to one asset). How would I go about doing this? The best case solution would be if I could have everything separated during the final build, this way if I update one tree asset I don't need to update *all* tree assets, but I'm not sure if this is possible.

Example Structure:
**+** A common set of assets that's loaded on startup (menu textures, trees used often, etc).
**+** A set containing trees, rocks, and other foliage.
**+** A set containing various scripts (AI scripts that would get updated frequently for example).

Thanks for the help!

# Answer
Easy indeed - you are looking for Asset Bundles, which you can read about here: https://unity3d.com/learn/tutorials/topics/scripting/assetbundles-and-assetbundle-manager

In pre-2017 versions, you simply set the asset bundle at the bottom of the inspector for each asset. In 2017, I believe there have been some changes to have a UI that allows you to set Asset Bundles with the Asset Bundle Browser: https://docs.unity3d.com/Manual/AssetBundles-Browser.html
> 3 votes

---
Tags: unity, assets, asset-management, distribution
---


title: Determining If a Point is Within Bounds

text:
# Question
Title: Determining If a Point is Within Bounds
I've got two points which I need to create a bounding box with, and then check to see if points are within this bounding box. The end result is a marquee selection tool.

So, here is the code I started with:

```
    var v1 = Camera.main.ScreenToViewportPoint( screenPosition1 );
    var v2 = Camera.main.ScreenToViewportPoint( screenPosition2 );
    var min = Vector3.Min( v1, v2 );
    var max = Vector3.Max( v1, v2 );
    //min.z = camera.nearClipPlane;
    //max.z = camera.farClipPlane;

    var bounds = new Bounds();
    bounds.SetMinMax( min, max );
    return bounds;

```

So then when I run it, it seems to create the correct bounds: Center (0.4,0.4,22.3), Extends (0.2,0.2,0.0)

And the point seems like it should be within: (0.4,0.3,22.4)

Now, my initial thoughts were that the z-index was off. However, i've tried setting that a bunch of different ways, including setting the z index of the center to 22, and the extent to 25. Nothing works.

I'm checking to see if it's contained, with:

```
bool unitInsideSelection = viewportBounds.Contains(camera.WorldToViewportPoint( gameObject.transform.position ) );

```

Where viewportBounds is the return object of the function above.

Any Thoughts?

# Answer
> 3 votes
This is an X/Y problem. You want to select something on the screen, right? So do things in screen space.

Get your point in the world in question `p_w`. Project it onto the screen giving `p_s` in pixels. Then check a pixel rectangle on the screen to see if it contains `p_s`. Easy right?

Here's some pseudocode.

```
// Tells if a point on the screen is within a rectangle given by min and max bounds.
bool contains(Point2 pointOnScreen, Point2 screenMin, Point2 screenMax) {
    return pointOnScreen.x <= screenMax.x &&
           pointOnScreen.y <= screenMax.y &&
           pointOnScreen.x >= screenMin.x &&
           pointOnScreen.y >= screenMin.y;
}

// Determines if a point in the world is within the bounds on the screen.
bool contains(Point3 pointInWorld, Camera camera,
              Point2 screenMin, Point2 screenMax) {
   // Project a point in the world to the screen. This gives a 3D
   // vector in pixels, with an added z depth.
   Point3 pointOnScreen = camera.projectToScreen(pointInWorld);
   return contains(pointOnScreen.xy, screenMin, screenMax) && pointOnScreen.z > 0;
}

```

# Answer
> 1 votes
From my understanding of your problem, building a selection marque function, you would follow this approach

1. Project test points p0, p1, ... to viewport space (or some surface) that is facing the camera.
2. Get viewport space (or surface) coordinates of two mouse points. These form the bounding box for selection marquee.
3. Use point-inside-rectangle test to determine if projected points are inside bounding box.

The easiest way to test if a 2D point is inside a rectangle is to test if all the 2D cross products are the same sign.

If b0, b1, b2, and b3 are the coordinates of your box, and your are testing if p is inside then you check that all the following are true.

cross( p - b0, b1 - b0 ) \> 0

cross( p - b1, b2 - b1 ) \> 0

cross( p - b2, b3 - b2 ) \> 0

cross( p - b3, b4 - b3 ) \> 0

I hope I understood what you are trying to do. Please correct me if I am wrong.

---
Tags: unity
---


# Question
Title: Help with understanding how the gamecontroller script works
I'm trying to understand the concept of game controllers and what all they're used for in different types of games. Are they mainly to control how the game operates? For instance, if I had an RPG that had a questing system, would it be the game controller that manages that? So what all should I consider when building a game controller? Is it everything that doesn't involve user input? Can anyone explain this to me, or at least point me in the direction to find this information?

To clarify, I'm not talking about physical game controllers, I'm talking about the game manager script you add to your game attached as a game object.

# Answer
> 5 votes
> For instance, if I had an RPG that had a questing system, would it be the game controller that manages that?

It would not be *the* game controller, it would be *a* game controller.

A controller is a class which notices when it's time to do something and then makes that happen. In the context of game development, each controller is usually responsible for one game feature. This is called the single responsibility principle. If you try to squeeze every single feature of your game into one controller, you will end up with a huge god object. In a very simple game you might get away with that, which is why many of the basic Unity tutorials follow that pattern. But if your game is more complex, then your controller-class will become so huge that it will be completely unmaintainable.

The controller for your quest system would be the `QuestController`. Its `Update`-method would check if the success-condition or failure-condition of any quest is met and when that is the case trigger whatever is supposed to happen in that situation.

When you delve deeper into Unity, you will encounter some controllers which are provided by the Unity engine itself and dedicated to specific engine features, like the `AnimationController` or the `CharacterController` .

> Is it everything that doesn't involve user input?

User-input would actually *also* be handled by a controller, which most people usually name `InputController` or `PlayerController`.

---
Tags: unity
---


# Question
Title: LibGDX FrameBuffer no Transparency when drawing
I try to draw severeal `Sprites` to a `FrameBuffer`. The `Sprites` are PNGs with transparency. When I draw them directly to the screen it's fine. But when I draw on the `FrameBuffer` and then draw the resulting texture on the screen the transparent parts are cut out and the glBackground shines through. Any idea how to solve this?

Here is how I do it:

```
FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, width, height, false);
Sprite fboTexture = new Sprite(frameBufferObject.getColorBufferTexture());
fboTexture.flip(false, true);

fbo.begin();
batch.begin();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.draw(sprite1, 0,0);
batch.draw(sprite2, 0,0);
batch.draw(sprite3, 0,0);
batch.end();
fbo.end();

batch.begin();
batch.draw(fboTexture, 0,0);
batch.end();

```

# Answer
> 0 votes
Ok I fixed it myself. I simply change the blend function before drawing the `FrameBuffer`.I change it to `batch.setBlendFunction(GL20.GL_ONE_MINUS_DST_ALPHA, GL20.GL_SRC_ALPHA)` and then change it back to `batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)`.

# Answer
> -1 votes
You may need to enable blending in the batch

```
batch.enableBlending();

```

---
Tags: libgdx, transparency, frame-buffer
---


title: LibGDX - Lighting without box2DLights

text:
# Question
Title: LibGDX - Lighting without box2DLights
I wanted to add some lighting effects to my game. The only way I know t achieve this is through a shader who calculates the lighting. But for multiple lightsources it's a bit complex at the moment. Is there an easier way to just create an overlay lighting effect?

# Answer
> 0 votes
You can simply darken the entire scene and add a kind of sprite lighting to the parts you want illuminated. For example this was used in the SNES Zelda and other games back in the day.

They would make the whole scene almost totally black in the caves for example and when you light a candle you get a bubble of light around you. Also torches on the wall would have the same sprite surrounding them.

Its not the best looking effect in the world but its sure easy and does add a nice little touch to 2d games.

Of course remember to add alpha channel for transparency of the light and this works best when the scene is very dark.

Im sure there are better solutions but this is one ive used in the past just to add a little touch to my games without using shaders / particle systems and other lighting effects

# Answer
> 1 votes
The answer to this related question on SO gives a simple solution to the problem. Use a texture like this (this one s CC0, use as you wish):

Then when you draw this sprite you blend it with the background:

```
batch.setBlendFunction(GL20.GL_DST_COLOR, GL20.GL_SRC_ALPHA); // Blend with background
theLightSprite.draw(batch, parentAlpha); // Draw the circle of light
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); // Normal rendering

```

---
Tags: libgdx, lighting
---


# Question
Title: save player achievements in local device
As an indie developer with zero dollar budget for servers and backend i wonder if there are ways to store the player achievements on his mobile device ?

# Answer
> 0 votes
You can always build offline achievements. Many games have internal achievements that are then presented to the external service (GameCenter, PSN, XBL, et cetera). Just make them a base part of your game, and if you're able to expand them to service-related achievements, you can always do so via an update later.

---
Tags: server, mobile, leaderboards, achievements
---


# Question
Title: Spatial Hashing is set up.. now how should I go about actual collision logic?
So I have a spatial hashing system set up and it works. It puts players in buckets based on their x/y/width/height

So I was going to check collisions on each frame when I loop through the entity for updating their physics. But how would I go about duplicate collisions? Say I'm checking for player a, which is in the same bucket as bullet a.. I check if there's a collision and there is, should I do the collision logic right there? Or should I add the collision to a list and iterate through that list at the end of the frame to handle the logic for each collision? This way I can also apply logic to prevent duplicate collisions. Or should I just do all the logic right there and then when the initial collision is made?

# Answer
> 1 votes
Check each entity against every entity that comes *after it* in the list, to prevent duplicate collisions. So if you are on entity `n`, check it against `n+1`, `n+2` etc. to the end of the list.

As to when you resolve your collision: that's up to you. I would recommend doing all detections first and then doing all your resolutions, in a way similar to what you recommend (add collisions that need to be resolved, to a list).

The problem is that if you resolve the collisions right then and there before you've finished checking for all collisions, you're modifying state which may (by some means or another) cause certain things to get missed. So best do this in two discrete phases.

---
Tags: collision-detection
---


# Question
Title: How to await player input using Coroutines
How can I accept player input using Coroutines, pausing execution of Unity while the player has not yet provided input? It seems like a simple problem, but I can't seem to figure it out. Here is my latest attempt. In this program I want to do some logic and pause in the middle, continuing only when the player has inputted some data. Someone please tell me I'm on the right track :O

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

public class InputTester : MonoBehaviour
{
    int choice = -1; // valid choices for this example are 0 and 1

    void Start()
    {
        StartCoroutine(DoSomeLogic());
    }

    IEnumerator DoSomeLogic()
    {
        print("Starting...");
        print("Awaiting your choice - 0 or 1. :: ");
        // yield return StartCoroutine(WaitForKeyDown(KeyCode.Alpha0) || WaitForKeyDown(KeyCode.Alpha1));
        // how to combine these two into a single method that gives the player a choice?
        print("Continuing...");
        switch (choice)
        {
            // logic based on the choice
        }
    }

    IEnumerator WaitForKeyDown(KeyCode k)
    {
        while (!Input.GetKeyDown(k))
            yield return null;
        SetChoiceTo(k);
    }

    private void SetChoiceTo(KeyCode keyCode)
    {
        switch (keyCode)
        {
            case (KeyCode.Alpha0):
                choice = 0;
                break;
            case (KeyCode.Alpha1):
                choice = 1;
                break;
        }
        //StopAllCoroutines(); // how do I stop all the coroutines that accept player input?
        print(choice);
    }
}

```

# Answer
try this, you simply give the WaitForKeyDown coroutine a list of keys to check, once it registers a key, it will exit the checking loop & terminate:

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

public class InputTester : MonoBehaviour {
    int choice = -1; // valid choices for this example are 0 and 1

    void Start() {
        StartCoroutine(DoSomeLogic());
    }

    IEnumerator DoSomeLogic() {
        print("Starting...");
        print("Awaiting your choice - 0 or 1. :: ");
        yield return StartCoroutine(WaitForKeyDown(new KeyCode[] { KeyCode.Alpha0, KeyCode.Alpha1 }));
        print("Continuing...");
        switch (choice) {
            // logic based on the choice
        }
    }

    IEnumerator WaitForKeyDown(KeyCode[] codes) {
        bool pressed = false;
        while (!pressed) {
            foreach (KeyCode k in codes) {
                if (Input.GetKey(k)) {
                    pressed = true;
                    SetChoiceTo(k);
                    break;
                }
            }
            yield return null; //you might want to only do this check once per frame -> yield return new WaitForEndOfFrame();
        }
    }

    private void SetChoiceTo(KeyCode keyCode) {
        switch (keyCode) {
            case (KeyCode.Alpha0):
                choice = 0;
                break;
            case (KeyCode.Alpha1):
                choice = 1;
                break;
        }
        print(choice);
    }
}

```
> 2 votes

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


# Question
Title: How to implement 2 cameras in a unique stage using LibGDX
I am quite new to LibGDX. I am trying to make a game, where the character is an `Actor`, and it's controlled by a `Touchpad`(included in the main `Stage` as an `Actor` too).

My problem is that I am trying to put the stage's camera to be always centered on the character, but I have no idea of how to solve this, I've been searching and it seems I have to use 2 cameras, 1 to show the controllers (the touchpad), and another to show the actors and that stuff, so while the actors are moving, the touchpad will keep on the screen, but I do not really know how should I do this, my code is this:

```
public class GameScreen extends BaseScreen {

    Stage stage;
    Character character;//it extends from actor
    Touchpad joystick;
    int screenWidht, screenHeight;
    Skin joystickSkin;

    public GameScreen(AwesomeTanks game) {
        super(game);
        screenWidht = Gdx.graphics.getWidth();
        screenHeight = Gdx.graphics.getHeight();

        joystick = new Touchpad(0,getTouchPadStyle());
        joystick.setColor(joystick.getColor().r, joystick.getColor().g, joystick.getColor().b, 0.5f);
        joystick.setBounds(10, 10, screenHeight / 2.5f, screenHeight / 2.5f);

        character = new Character();

        stage = new Stage();
        stage.addActor(character);
        stage.addActor(joystick);

        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void hide() {
        stage.dispose();
        joystickSkin.dispose();
        character.detach();

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1f, 1f, 1f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        character.moveBy(joystick.getKnobPercentX() * character.velocity * delta, joystick.getKnobPercentY() * character.velocity * delta);

        if(joystick.isTouched())
            character.setRotation((float) ((180/Math.PI)*Math.atan2(joystick.getKnobPercentY(),joystick.getKnobPercentX())));

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
}

```

# Answer
> 1 votes
You need to create another "UI" `Stage` and call its `act` and `draw` methods in the `render` method. You also need to use a `InputMultiplexer` to process the input of both `Stages`.

The "UI" `Stage` should use a `ScreenViewport` as well, to support multiple screen sizes and densities.

More info about Viewports here:

# Answer
> 0 votes
You can make two view port and each time call batch.setProjectionMatrix and then draw textures in the camera you want

```
mainCamera = new OrthographicCamera(Constants.CAM_WIDTH / Constants.PPM, Constants.CAM_HEIGHT / Constants.PPM);
    mainViewport = new FitViewport(Constants.CAM_WIDTH / Constants.PPM, Constants.CAM_HEIGHT / Constants.PPM, mainCamera);
    mainCamera.position.set(Constants.CAM_WIDTH / (Constants.PPM * 2f), Constants.CAM_HEIGHT / (Constants.PPM * 2f), 0);
    mainCamera.update();
    secondCamera = new OrthographicCamera(Constants.CAM_WIDTH / Constants.PPM, Constants.CAM_HEIGHT / Constants.PPM);
    backgroundViewport = new FitViewport(Constants.CAM_WIDTH / Constants.PPM, Constants.CAM_HEIGHT / Constants.PPM, secondCamera);
    secondCamera.position.set(Constants.CAM_WIDTH / (Constants.PPM * 2f), Constants.CAM_HEIGHT / (Constants.PPM * 2f), 0);
    secondCamera.update();

```

And then in the render method use:

```
    //For the bacground cam
    batch.begin();
    batch.setProjectionMatrix(secondCamera.combined);
    backgroundManager.render(delta);
    //For the main cam
    batch.setProjectionMatrix(mainCamera.combined);
    platformManager.render(delta);
    doodleGuy.render(delta);
    batch.end();

```

---
Tags: java, android, libgdx, camera, android-studio
---


# Question
Title: SteamVR_TrackedObjects disabled on dashboard
our game relies heavily on some Joints attached (not childs) to the tracked controllers. But those controllers get disabled when a user clicks on the system button which actually break our physics when user get back in game.

Is there a way to keep them active ? i checked they get Disabled in SteamVR\_ControllerManager and could just risk commenting that block.

Or any event method called when the user opens the VR Dashboard ?

Thank you.

We are using Unity 5.6.0 and the latest SteamVR plugin.

# Answer
I first tried commenting those two methods that appear in SteamVR\_ControllerManager.cs line 130

```
// Reparents to a new object and deactivates that object (this allows
// us to call SetActive in OnDeviceConnected independently.
private void HideObject(Transform t, string name)
{
    if (t.gameObject.name.StartsWith(hiddenPrefix))
    {
        Debug.Log("Ignoring double-hide.");
        return;
    }
    var hidden = new GameObject(name).transform;
    hidden.parent = t.parent;
    t.parent = hidden;
    hidden.gameObject.SetActive(false);
}
private void ShowObject(Transform t, string name)
{
    var hidden = t.parent;
    if (hidden.gameObject.name != name)
        return;
    t.parent = hidden.parent;
    Destroy(hidden.gameObject);
}

```

Even if it didn't break anything in our Q&A and testings. we kept them as is but instead attached a script on our SteamVR Rig anchors that attach those Joints during the OnDisable() and detach them on OnEnable().
> 1 votes

---
Tags: unity, steam, htc-vive, steam-vr
---


# Question
Title: Why aren't my 2D primitives visible using a custom effect?
I'm working with Monogame and rendering a triangle using the following code.

```
vertices = new []
{
    new VertexPositionColor(new Vector3(100, 200, 0), Color.White),
    new VertexPositionColor(new Vector3(200, 100, 0), Color.White),
    new VertexPositionColor(new Vector3(300, 200, 0), Color.White),
};

graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1);

```

Ordinarily I'd apply a `BasicEffect` before the draw call, but this time I'm using a custom effect. For testing, I wrote the following shader code to return solid green for each pixel within the triangle.

```
struct VertexShaderInput
{
    float4 Position : POSITION;
    float4 Color : COLOR;
};

struct VertexShaderOutput
{
    float4 Position : POSITION;
    float4 Color : COLOR;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Color = input.Color;
    output.Position = input.Position;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR
{
    return float4(0, 1, 0, 1);
}

technique Technique0
{
    pass Pass0
    {
        VertexShader = compile vs_4_0_level_9_1 VertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
};

```

The problem is that, although the shader compiles successfully, nothing shows up.

**Why is my triangle invisible using this shader?**

Based on my understanding of vertex and pixel shaders, the above HLSL code should work correctly. In the vertex shader, since (for the moment) I'm working in strictly 2D without a camera, no transformations need to be done on the vertices (i.e. they're already in screen space). From there, the pixel shader simply returns solid green for each pixel. I've also ruled out potential backface culling issues by swapping the order of vertices, and I've tried using different semantics on my HLSL structure variables. No luck.

Shaders still feel uncomfortable to me, but I feel my logic is correct based on what I've read. If that's the case, there must be some weird quirk I'm not aware of in having these HLSL shaders work at all, apart from the logic. What am I missing? Is there a better way to debug these problems short of changing random variables and hoping for the best?

# Answer
The problem you are having is that 'no transform' coordinates are not in pixels. They are in normalized device coordinates which range from -1 to 1. If you want to specify your vertices in pixel coordinates, you need a transformation which converts that to normalized device coordinates with a scale and offset.

For example in DirectX Tool Kit's `SpriteBatch`, this function computes a matrix to do just that:

```
// Generates a viewport transform matrix for rendering sprites using x-right y-down screen pixel coordinates.
XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ ID3D11DeviceContext* deviceContext, DXGI_MODE_ROTATION rotation )
{
    // Look up the current viewport.
    if ( !mSetViewport )
    {
        UINT viewportCount = 1;

        deviceContext->RSGetViewports(&viewportCount, &mViewPort);

        if (viewportCount != 1)
            throw std::exception("No viewport is set");
    }

    // Compute the matrix.
    float xScale = (mViewPort.Width  > 0) ? 2.0f / mViewPort.Width  : 0.0f;
    float yScale = (mViewPort.Height > 0) ? 2.0f / mViewPort.Height : 0.0f;

    switch( rotation )
    {
    case DXGI_MODE_ROTATION_ROTATE90:
        return XMMATRIX
        (
             0,       -yScale,  0,  0,
             -xScale, 0,        0,  0,
             0,       0,        1,  0,
             1,       1,        0,  1
        );

    case DXGI_MODE_ROTATION_ROTATE270:
        return XMMATRIX
        (
             0,       yScale,   0,  0,
             xScale,  0,        0,  0,
             0,       0,        1,  0,
            -1,      -1,        0,  1
        );

    case DXGI_MODE_ROTATION_ROTATE180:
        return XMMATRIX
        (
            -xScale,  0,       0,  0,
             0,       yScale,  0,  0,
             0,       0,       1,  0,
             1,      -1,       0,  1
        );

    default:
        return XMMATRIX
        (
             xScale,  0,       0,  0,
             0,      -yScale,  0,  0,
             0,       0,       1,  0,
            -1,       1,       0,  1
        );
    }
}

```
> 1 votes

---
Tags: shaders, monogame, hlsl
---


# Question
Title: Unity find position within range of object
Say you have a gameobject that is at a certain position(this could be your player).

Now say that you have a melee NPC that has to be within a certain range to hit the Player.

Now you would do something like this to find out where the player is:

```
var targetPosition = target.transform.position;

```

Say that the range of the NPC is 4 meaning he can be 4 units away from the player before he can start attacking him.

My question is how would you subtract that to get a position that is within range?

And am i doing this type of thing correctly? or is there a better way of doing it? :)

Any help would be appriciated a lot!

# Answer
Use Vector3.Distance to get the distance between two positions.

```
float distanceToTarget = Vector3.Distance(playerPosition, targetPosition);
float distanceThreshold = 4f;
if (distanceToTarget <= distanceThreshold) {
    // Attack
}

```
> 1 votes

---
Tags: unity, vector
---


# Question
Title: Unity is reseting Dictionary when game is playing
I have a class named Item, I am storing instances of this class in list. List is created before game starts, everything works fine in that moment but when I am playing, items still are in list but components Dictionary in each seems to be reset because it haven't got any elements, before game it has.

This is my Item class:

```
[Serializable]
public class Item
{
    public string Name { get; }

    private Dictionary<Type, ItemComponent> components = new Dictionary<Type, ItemComponent>();

    public comp GetItemComponent<comp>() where comp : ItemComponent
    {
        Debug.Log(components == null); //in game shows true

        return
             components.Values.OfType<comp>().FirstOrDefault();
    }

    public Item AddItemComponent(ItemComponent component)
    {
        components.Add(component.GetType(), component);
        return this;
    }

    public Item(string name, string imagePath)
    {
        //components = new Dictionary<Type, ItemComponent>();

        Name = name;
        ImagePath = imagePath;
    }

}

```

I am not reset or changing items during game.

What could be the problem? Is it connected with Unity serialization limitations?

# Answer
> 2 votes
In Unity, Dictionaries are not serialized out of the box, so if they were populated in the Editor, they become cleared when the game starts.

You will want to run your `AddItemComponent` method at runtime as necessary to repopulate your Dictionary.

There might be plugins around to help make Dictionaries serializable (or at least classes similar to Dictionary), but you'd have to look around. Check this thread too.

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


title: Help with transform.lookat and camera?

text:
# Question
Title: Help with transform.lookat and camera?
```
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(mousePos);

```

This will actually make the camera follow the mouse, but it goes crazy, the camera seems to spin in circles rapidly : here is actually a gif of what is happening. https://gyazo.com/952da6c28e644b7b0e6500a597b6804e/preview Could anyone help me figure how how to fix it?

# Answer
> 0 votes
ScreenToWorldPoint is a point in 3D space that's basically at the cameras position. That's why it's flipping out.

try something like

```
mousepos += (camera.transform.forward * 100);

```

to actually get the point further away from the camera.

The 100 here is arbitrary.

Edit:

This will not make the camera orbit if that's what you want. Check the Unity Standard Assets for prescripted camera scripts.

---
Tags: unity, transformation
---


# Question
Title: How to make Buttons work on mobile in Unity
I am working on a 2D Platformer for mobile in unity. On the main menu screen I have two buttons. One is play and the other is quit. I am just wondering how would I make the buttons take a touch input once it is on the phone. I did switch the build to Andorid. is that all that is needed or is there something else? I am doing the project in c#.

Thanks!!!!!

# Answer
> 1 votes
Yes that is all that is needed. It will take touch input on phones.

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


# Question
Title: Turning On/Off Vsync no longer working when rendering to an offscreen buffer
I have this reaallly strange issue that as soon as I render to an offscreen framebuffer I am no longer able to toggle VSync while my application is running. I am using OpenTK as the opengl wrapper, but I have a strong feeling it's not related at all to OpenTK.

The odd thing is I can still turn VSync on/off during startup of the application, but not anymore while the game is running. If I temporarily redirect rendering to the default framebuffer i can also again toggle Vsync.

I can use an ugly hack to just redirect rendering to the default framebuffer, a frame later set toggle vsync mode, then redirect rendering to the offscreen framebuffer again, however I would much prefer a proper fix.

Here's some pesudo code what my code does:

```
Initialize 2 Framebuffers. Bind first offscreen framebuffer.
while(!exit) {
    Render opaque stuff
    Switch to second framebuffer for transparent objects
    Render transparent stuff
    Switch to first buffer
    Render transparent texture to primary buffer
    Switch to default framebuffer (default FB in write mode, first FB in readmode)
    Blit from first to default framebuffer
    Bind first offscreen FB
}

```

I had to use offscreen frame buffers in order to re-use the depth buffer in the transparent render pass for implementing WOIT (Weighted Blended Order Independent Transparency)

# Answer
Oddly enough, after switching to 64bit builds this problem disappeared.
> 0 votes

---
Tags: c#, opengl, opentk, vsync
---


# Question
Title: glClearBuffer takes 1 second on a Geforce 9500GT
These 2 lines (in C# using OpenTK) seem to cause 1 second lag every frame on a machine with a Geforce 9500 GT

```
GL.ClearBuffer(ClearBuffer.Color, 0, new float[] { 0, 0, 0, 0 }); // accum
GL.ClearBuffer(ClearBuffer.Color, 1, new float[] { 1, 0, 0, 0 }); // reveal (only red)

```

The framebuffer in question has 2 color attachments (Rgba16f and R16), and one depth attachement. The framebuffer status after setup indicates no problems.

This is also just one of 3 framebuffers that are cleared every frame - only this one turns the my game into a diashow. There is no such problem on any other card I've tested. Before clearing both color attachment are bound using

```
DrawBuffersEnum[] bufs = new DrawBuffersEnum[] { DrawBuffersEnum.ColorAttachment0, DrawBuffersEnum.ColorAttachment1 };
GL.DrawBuffers(2, bufs);

```

How could a very particular gfx card be so slow in clearing 2 color attachments? o.O

# Answer
> 2 votes
The problem was that I used ushorts in one of my VBOs to save a bit on memory, but seems to be very costly when doing lookups on certain AMD cards. After switching back to full integers the performance drop was gone.

---
Tags: c#, opengl, opentk, frame-buffer
---


# Question
Title: How to limit velocity of object on touchDragged event?
I am using the current code to handle the movement of the player ship in my libGDX game:

```
if (playerShipTouched)
{
  position.x = screenX - touchOffset;

  // limit movement to screen bounds
  if (position.x < 0)
  {
    position.x = 0;
  }
  else if (position.x > (globals.VIRTUAL_WIDTH - playerShipSprite.getWidth()))
  {
    position.x = globals.VIRTUAL_WIDTH - playerShipSprite.getWidth();
  }
}

```

This gives me 1:1 screen to touch movement of the ship. However, I would prefer to limit the movement velocity so the ship can't just skip to the other end of the screen if the user moves their finger fast enough. I tried something like this:

```
position.x = position.x + Math.signum(screenX - position.x) * 800 * Gdx.graphics.getDeltaTime();

```

The movement is correctly restricted, but is jerky. Any ideas?

***edit***

Additional overridden touch methods:

```
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
    touchPos.x = screenX;
    touchPos.y = screenY;
    touchPos.z = 0;

    camera.unproject(touchPos, globals.resizeViewport.x, globals.resizeViewport.y,
            globals.resizeViewport.width, globals.resizeViewport.height);

    // Did the player touch the ship?
    touchRect.x = position.x;
    touchRect.y = position.y;

    if (touchRect.contains(screenX, screenY))
    {
        playerShipTouched = true;
        touchOffset = screenX - position.x;
    }
    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
    playerShipTouched = false;
    return false;
}

```

# Answer
You can use the MathUtils.lerp function to interpolate between current position and target position. Reduce the final argument until you get a smooth movement.

```
position.x = MathUtils.lerp(position.x,(screenX - touchOffset),0.2f)

```

Another option could be to add a speed cap on the player.

```
float speed = 16f;
if((screenX - touchOffset) < player.x){
    player.x-= (speed  * Gdx.graphics.getDeltaTime());
}else if((screenX - touchOffset) > player.x){
    player.x+= (speed  * Gdx.graphics.getDeltaTime());
}

```
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Should a bowling game use a 2d or a 3d physics engine?
I'm creating a bowling game in flash+as3. I'm new to physics engines, so, to start I've begun to learn Box2D since I've heard it's one of the most popular physics game engines.

Currently, I'm not sure if it's the best solution. I'm not sure even if I should use a 2D physics engine or if I should move to 3D physics engine.

As you can see in the attached screenshot of my game, the ball should move on the lane until it hits the pins. The game has some amount of 3D behavior.

Please advise.

# Answer
> 4 votes
When developing games it is important to separate the game *mechanics* from the game *representation* on the screen.

The game mechanics of bowling can be simplified to a pure 2d simulation by looking at the game from above:

You wouldn't lose *too* much of the core gameplay of bowling by not allowing the ball and pins to jump up from the lane. But using a 3d physics engine would certainly help to make the game more realistic, especially when it comes to handling pin-with-pin collision.

But *simulating* the game from above does not necessarily mean that you need to *render* it from above.

Your physics engine should give you just coordinates (x:y or x:y:z, depending on whether you use a 2d or a 3d engine). What you do with those coordinates is up to your rendering loop. A pseudo-3d representation with 2d drawing technology like in the mockup in the question is certainly possible (a common term for this is "2.5d"). You will have to translate the coordinates on the lane to screen coordinates yourself, though, by taking perspective shortening into account (divide width and height of objects by their distance from the viewer). A 3d rendering engine would do that for you, but it is not too difficult to do it on your own. Open a new question if you need help.

Bottom line: You can combine a 2d physics engine with a 3d rendering engine or a 3d physics engine with a 2d rendering engine.

---
Tags: physics, box2d, actionscript-3, physics-engine
---


# Question
Title: Array-based tilemaps and bounding box (aabb?), how to do efficient tile collisions?
At one point in my game I had every tile as it's own object, so that I could use standard AABB collision testing easily. I later realized this was horrible for performance and simply made my tiles be an array of numbers denoting which 16x16 segment to use.

However, this also means that I can no longer use standard AABB collision testing for tilemaps, since tiles don't have their own AABBs anymore. The first method I've tried is using hotspot collisions (per-pixel, see this page), but I'd really like to instead use some kind of bounding-box based collision testing instead of manually placing hotspots. The only methods I can think of are horrible for performance; using separate AABBs for tiles (already tried) and checking every singe pixel inside a bounding box / AABB for collision with a tile (likely even worse for performance).

What is a way that I can detect collisions using my character's bounding box while keeping my tiles simply an array of numbers, and not having a large performance impact?

# Answer
> 4 votes
The reason there isn't a standard AABB or partition strategy for tile-based maps is that it's already easier to detect collisions against it than using AABBs.

```
static int TILE_WIDTH=16, TILE_HEIGHT=16;
Tile[,] map;

class Character {
   int width, height;
   int x, y;
   bool isColliding () {
       for(var i = this.x; i < this.x + this.width; i += TILE_WIDTH)
       for(var j = this.y; j < this.y + this.height; j += TILE_HEIGHT) {
           if (map[x / TILES_PER_UNIT, y/TILES_PER_UNIT] != Tile.Empty) {
               return true;
           }
       }
       return false;
   }
}

```

# Answer
> 0 votes
I don´t see a problem having an AABB for your Tiles (if you don´t want to have 1 AABB for each Tile in your game you can use Flyweight pattern to minimize the memory usage(but only if you want to have the tiles of the same size)- Flyweight pattern describtion). But I think keeping an AABB for every tile is not a big memory hurt these days.

To minimize the number of the collision checks I would suggest you some kind of **spatial partition** (there are many ways to implement it) - Spatial partition explanation. Basically this drastically helps to improve the performance because instead of checking collisions between all the objects you check the collision only between the objects in the same grid.

# Answer
> 0 votes
I know of a program called Tiled that allows you to easily create a tile map. The program features object layers, which can allow you to customize bounding boxes. You can use these to create a shape around an entire group of tiles, so that instead of checking for each individual tile, you can collide with the entire group as a whole. You'll need to figure out how to load TMX files, but they are in XML format so it's really not that hard.

Link here

---
Tags: collision-detection, tilemap, bounding-boxes, aabb, tiles
---


# Question
Title: SDL zooming/upscaling without images becoming blurry?
I'm working on a game with 32px tiles and I have one question regarding this and scaling. When I try to see my game fullscreen my image just becomes blurry. I remember playing NES games and when the image was scaled you just saw pixels as big blocks but they were still as crisp as when they were small, so I'm wondering how I can do this in SDL.

# Answer
> 1 votes
As far as I know, this is not a standard feature of SDL. It is (if I remember correctly) a feature in SDL2\_gfx(an extension library made specifically for linux) and OpenGL.

However, if you would like to multiply your image's size by a whole number (n), you could do so by reading each pixel and assigning that color value to a square that is (n)-times larger than a single pixel. This would work best for small sprites, rather than large and complex images. I have not implemented this myself, but theoretically it sounds straight-forward.

# Answer
> 5 votes
If you make the scale an integer number, like 2 here

```
SDL_RenderSetScale(renderer, 2)

```

then every pixel will scale up to an integer number of pixels. There's then no need for anti-aliasing between pixels and hence no blurriness.

# Answer
> 3 votes
What you'll be after is an image scaling algorithm. You can do this using plain (as in CPU) code, which is very slow, or I believe many scalers are available as GPU shader programs. This is especially suitable for you, as it sounds like you are working with low-resolution pixel art and you want to upscale them without introducing blurriness.

The simplest algorithm is nearest-neighbour but it tends to introduce blockiness, which may or may not be what you want. Typical pixel scalers will try to look for line patterns and preserve them. See this example (original is in the middle, nearest neighbour on the left, 2xSaI on the right):

hqx is also a popular choice as code is very easy to find for it these days, and it's fairly high quality. The state of the art includes xbr and Kopf-Lischinski.

These scalers are commonly found in console emulators, some of which are open source so you can easily take a look at how it's done.

# Answer
> 2 votes
The current implementation of SDL 2.0 allow you to do that natively. Read in the Migration Guide The section called **Setting up a game with the new video API** and see how the flag `SDL_WINDOW_FULLSCREEN` and function `SDL_RenderSetLogicalSize` will help you on this.

You don't have to make any software algorithm to do that. Believe me I like to write direct pixel access runtines.

In general, if you are using any 3D API textures you should be allowed to set te Texture filtering to "Point" (Nearest-neighbor interpolation) instead of the default Bilinear or Anisotropic wich are the filters that make your texture blurred when scaled.

Is just scaling your texture without interpolated filtering, like in the old days of DOOM and Tomb Rider I without accelerated graphics.

See this examples of OpenGL texture filters; how they use the `GL_NEAREST` flag.

# Answer
> 0 votes
I know this is an ancient question, but since I came across this in google I'll drop in this answer. What you want to do (if you are using SDL2), is to initialise your application with this scaling hint:

`SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");`

https://wiki.libsdl.org/SDL\_SetHint

The images will look best scaled by a whole number.

---
Tags: graphics, sdl
---


# Question
Title: In Unity, rotating character spine keep going back to original rotation
this is the code for rotating spine in my character model:

```
Transform spine;
float horzMovement;

void Awake() {
    spine = transform.Find("Character/Healthmale/Root/pelvis/spine_01");
}

void Update() {
    horzMovement = Input.GetAxis("Mouse Y");
}

void LateUpdate() {
    spine.localRotation = Quaternion.Euler(
        spine.localEulerAngles.x + horzMovement,
        spine.localEulerAngles.y,
        spine.localEulerAngles.z
    );

    print(horzMovement + " / " + spine.localRotation.eulerAngles.x + "    " + Time.time);
}

```

Code is quite simple, I'm just rotating "X" axis from y mouse movement. The problem is when running this code, it seems work but it keeps rotating back to the original rotation.

This is the log that I printed into the console. Note that spine's original x rotation is about 27.62928.

```
0 / 27.69298    4.510662
0 / 27.69298    4.527147
-0.1 / 16.33139    4.543715    // minus movement detected
-0.1 / 16.3314    4.560284
-0.1 / 16.33139    4.57685
-0.1 / 16.33139    4.593714
-0.1 / 16.3314    4.609998
-0.1 / 16.33139    4.626548
-0.1 / 16.33139    4.643115    // but it seems not much changed, why?
-0.15 / 10.51222    4.659858
-0.15 / 10.51222    4.676248
-0.15 / 10.51222    4.692952
0 / 27.69298    4.759083       // this is when I stopped the mouse. It's reset.
0 / 27.69298    4.775648

```

As you see the above log, first time, it prints 27.692.. and it's original x rotation of spine.

Next, I moved my mouse so the "horzMovement" value was updated to minus, and it updates x localRotation also.

But when I stopped move mouse, it just return to initial x rotation 27.69298!

There is no code or functionality to "rotating back" to original rotation of spine. I don't know why this is happening. Wham am I missing?

Any advice will very appreciate it!!

# Answer
I solved this problem by follow DMGregory's saying: "Accumulate the desired rotation yourself rather than counting on it persisting frame to frame unchanged after animation".

This is the code:

```
Transform spine;
float horzMovement;
float prevSpineX;

void Awake() {
    spine = transform.Find("Character/Healthmale/Root/pelvis/spine_01/spine_02/spine_03");
    prevSpineX = spine.localEulerAngles.x;    // Save initial X rotation of spine
}

void Update() {
    horzMovement = -Input.GetAxis("Mouse Y");    // Invert direction so that aiming down results look down!
}

void LateUpdate() {
    spine.localRotation = Quaternion.Euler(
        prevSpineX + horzMovement;    // Calculate new x rotation by adding mouse movement and previous spine's X rotation
        spine.localEulerAngles.y,
        spine.localEulerAngles.z
    );

    prevSpineX = spine.localEulerAngles.x;    // Update previous x rotation to current rotation
}

```

I hope answer might help your problem. Special thanks for DMGregory who gaves me a good advice!
> 3 votes

---
Tags: unity, rotation, rigging, bones
---


# Question
Title: When creating a UI scene in Unity, should I render the canvas in camera space?
I'm working on a scene that is strictly going to be used for character creation. Can anyone explain what the best practice is for a scene like this? Should I render the canvas to the camera, or should I render it in world space, or as an overlay?

# Answer
> 2 votes
I'm guessing for your purposes, you're going to want to use screen space overlay.

Take a look at the Unity Manual: https://docs.unity3d.com/Manual/UICanvas.html

You probably don't want your UI to be affected by perspective, and you don't have any reason for the camera to move and have your UI not move with it, which is what you would use world space for.

---
Tags: unity, camera
---


title: Ray tracing and Z buffering in graphics

text:
# Question
Title: Ray tracing and Z buffering in graphics
I am a high school student taking computer science as a subject, and someone who is very interested in the game development industry. I am currently writing an essay on Raytracing and Z-buffering by comparing them and deducing the right situation for each of them. I was wondering if the developers could help me answer a question of in what specific situations those two are used specifically. I already know how both of them work. Also, do developers prefer another method than these two or is there a way to combine both to make an even more efficient 3D graphics algorithm? Thanks a lot!

# Answer
"Z-buffers" and "raytracing" are not mutually exclusive. Z-buffers are frequently used to support *triangle-based, back-projected rendering* (though they are optional in actual usage), and they can also be used to support raytracing. Equating z-buffers to traditional GPU polygon-based, back-projected rendering, just because these are often found together, **is outright erroneous**.

So, let's talk about Ray-tracing vs. the traditional GPU rendering pipeline, which *includes* Rasterization (see other wayward answers here) as one of its steps.

**Practical pros of traditional triangle-based rendering**

* Can use familiar pipelines and traditional, mature tools like 3DS Max, Maya, Blender to produce 3D content;
* There are countless resources available for it
* Processing is very fast on current hardware
* Doesn't do realistic lighting as well raytracing since the z-buffer it relies on is a boolean concept - you've either drawn at a nearer depth or you haven't, so composing individual pixels according to different factors at that screen point is difficult;
* It will not require arcane / cutting edges technologies to implement (speaking relatively, of course)

**Practical pros of raytracing**

* It can be an extremely accurate way of reproducing real-world lighting conditions
* It is conceptually quite a lot easier to understand and implement than the traditional approach
* Since hardware doesn't currently support it specifically (EDIT: This is no longer or only partly true, with the advent of NVidia RTX), you get to write your own implementation which means you understand everything that is going on i.e. how each pixel is composed (also a con, but a lot of fun and direct control over end appearance).

**Answer**

If you want to produce a game quickly, use the former. If you are cutting edge, want a highly individualised art style and have the time to build and endlessly tweak your graphics engine yourself, use the latter. Presently, since time is always of the essence in industry, most prefer the former.
> 5 votes

# Answer
Daniel beat me to it but I'm gonna give my own answer anyway since I had fun writing this. His bullet points are solid but I wanted to expand a bit more.

I'm going to use the term Rasterization rather than Z-buffering.

Raytracing is often used for "offline" rendering. Raytracing algorithms give very good pixel quality at the cost of high execution time. Because Raytracing algorithms simulate a light model very similar to the real world, phenomenon such as shadows, reflection and refraction are all very intuitive and simple operations. However since it takes a long time to calculate how a ray of light bounces and interacts with a scene for every pixel (1920x1080 pixels is a lot!) it's not practical to use Raytracing for real-time applications on the CPU. However because the pixel quality is high, "offline" or non-realtime applications use Raytracing extensively. RenderMan by Disney/Pixar which is a good example of an application that uses Raytracing for Film and Animation.

Most GPUs are designed to rasterize triangles to the screen, not to raytrace a scene. PowerVR by Imagination is a series of GPUs that perform hardware Raytracing but that's the exception rather than the rule (and they just lost a lot of market share since Apple is no longer using their GPUs).

I highly suggest you read up on modern GPU pipelines. Along with some reading it's a good idea to try to visualize the pipleine. A fun way to do this for yourself is to take a capture from your favorite game with something like RenderDoc and walk through the different pipeline stages and see what they do.

In recent years there have been two major developments that you may want to read up on. Pathtracing, as an alternative approach to raytracing has been a really popular area of research. Also as Daniel mentioned we've been seeing more and more short-raytracing algorithms being used in compute shaders on the GPU. Volumetric Fog in CryEngine and Lumberyard is generated by Compute shaders on the GPU that execute very short 1-bounce rays. The rays are executed in parallel on the GPU so the operation only takes a couple milliseconds but the results are pretty good.

If you're curious about modern game rendering techniques I suggest reading the articles here. These are a bit dense and very technical but they should give you an idea of the sort of crazy things people have to come up with to get rasterization on modern GPUs to produce realistic visuals.
> 1 votes

# Answer
To put it simply:

* Z-Buffering
    + Pro: Fast, it's what modern graphics cards tend to be designed around.
    + Pro: It's easy to implement.
    + Con: Getting realistic results isn't necessarily easy.
* Ray Tracing
    + Pro: Super easy to implement.
    + Pro: Lighting just works. Things like reflection and refraction are pretty much just going to happen.
    + Pro: Can get realistic results very easily.
    + Con: Can be extremely slow, especially with regards to multiple reflections on the rays. And by slow, I mean potentially multiple seconds, minutes or hours for a single frame.
    + Con: Most PC hardware isn't designed to speed this up much. Hardware that does can be very expensive.

Z-buffering is the domain of games and other home computer stuff, mainly because it's so fast to do. Ray-tracing, on the other hand, is more for 3D artists and people in the CG industry as they can afford to wait minutes or hours for a single frame.

For your second question, recent progress in graphics, particularly with deferred rendering, has enabled graphics developers the ability to use some ray tracing techniques in a Z-buffered system for effects like screen-space reflection and shadowing. These are often used with deferred rendering, rather than forward rendering, as shader writers have a lot more detail to perform the ray tracing (Technically ray marching) with. That doesn't mean it can't be done in forward rendering methods, but it tends to be a bit costlier.
> -1 votes

---
Tags: algorithm, graphics-programming, depth-buffer, raytracing
---


title: Good ways to indicate enemy toughness

text:
# Question
Title: Good ways to indicate enemy toughness
Can you add any good ways to indicate enemy strength to this list:
\- physical size
\- equipment quality
\- narration or preview scene
\- demeanour

**Background**
I'm designing a spell-casting/stealth game where some enemies are cannon-fodder, others are decent fights, and some (initially) will be lethal - hence the stealth requirement.
It's a VR title so I don't want UI elements (like stars, health-bars etc) messing up the immersion.
At the moment my inclination is to avoid cartoony art style so it'll be as 'realistic' looking as I can manage while keeping 90fps.

# Answer
## Design

This is the obvious one. The graphical aspect of a monster is very important and should tell the player if an enemy is strong or not (in some cases you want to do the opposite effect but let's pass on this). You can play on different aspects such as :

* The face : if he has big teeth, an angry look etc, it will indicate that he's not a really friendly enemy
* The size : let's face it, bigger monsters tend to be stronger. They do not have to be more agressive (ex. elephants) but they will be more resistant.
* The weapons : weapons tell perhaps more than physical aspects. Just picture a cute teenager girl with a rocket launcher ... well, you get the point.

## Color code

Many games work with color codes to indicate if a enemy is dangerous or not at all. For instance in the tower defense Bloons the color of the enemy represents the number of health points the enemy have (red : 1, blue : 2, etc.).

This is a very basic example but it could be a possibility. Green generally means peaceful, red means dangerous, black will be the deadliest enemy.

## Music and sounds

This aspect if often left behind but to my mind it's really important. If you have an area where the music is peaceful you can expect to have peaceful mobs but if the music gets epic all of a sudden (such as in Dark Souls) you know you are going to face some kind of boss or really tough monster.

Enemy noises, dialogs or screams/roars/.. could be a hint about their strength too.
> 3 votes

# Answer
I want to present an experimental idea for this.

## Concept

Since you are using VR, might it be possible to use some blurring/focal techniques like in cinema.

As an example, if you have a single lethal enemy among others, when that enemy enters the center field of view, blur the other lesser enemies and make the lethal enemy very clear with even maybe a small bit of zoom or enlarging. Perhaps increase the contrast in colors on that enemy specifically.
This might work best in stealth parts, where the player is likely to be taking their time and observing.

The reverse could work as well, depending on setting. If a lethal enemy is presented as some unknowable horror, or something beyond immediate comprehension, you could cause it to be harder to focus on. This simulates part of an adrenaline rush from panic where your pupils dilate and hence your vision blurs.

## Potential Issues

* Nausea: it's already an issue with VR, I'd suspect this wouldn't help unless the effect is balanced very well
* Timing and position: How long does a player have to have something in their field of view before this effect happens? Does it have to be in the center, or does it work at periphery as well?
* Tracking/Movement: Once the player looks away, does the effect persist? For how long?
* Gameplay Impedance: Will this affect prevent the player from interacting with other game elements?

Again, this is an experimental suggestion. I'm not aware of any games using this concept with VR. But I'd certainly like to see if it could work.
> 1 votes

---
Tags: game-design, virtual-reality
---


# Question
Title: How to set up flatbuffers in Android Studio - Gradle?
Just switching over from Eclipse to Android Studio. I think I'm supposed to use Gradle to automatically download dependencies from the web. Sounds great, but I can't get it working with anything, in particular Google's flatbuffers.

So I found the link on the Maven repository, and I think I'm supposed to do something with the following:

```
// https://mvnrepository.com/artifact/com.github.davidmoten/flatbuffers-java
compile group: 'com.github.davidmoten', name: 'flatbuffers-java', version: '1.3.0.1'

```

But the comments in my project's Gradle (which is supposed to be a library by the way - but that's another story...) says I should not place my "dependencies here" (see below)

```
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

```

So what am I supposed to do? I've heard of "modules" - so I could load flatbuffers in as a module?

# Answer
> 1 votes
I was updating the wrong build.gradle. I was updating the gradle of the package within the "app". So having updated my `build.gradle` file (Module: app) to include the following last dependency:

```
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile group: 'com.github.davidmoten', name: 'flatbuffers-java',
 version: '1.3.0.1'
}

```

it works nicely. Beginning to like AS now... hehe.

**UPDATE**

Been porting my stuff over to Android Studio today. I'm a total convert - very good and much easier than Eclipse.

---
Tags: android-studio, eclipse, gradle
---


title: Inconsistent jump height

text:
# Question
Title: Inconsistent jump height
I am doing some physics for a platformer game in MonoGame. The jump height changes based on FPS even though I'm using delta time. When the FPS decreases and gravity is added before movement, the jump height is shorter than usual. How do I keep a consistent jump height at all frame rates?

Here's the pseudo-code executed each frame:

```
velocity.Y += gravity * dt;
Move(velocity * dt);

```

# Answer
> 1 votes
The most commonly used method in commercial engines is the semi-implicit Euler method that I'm already using as you can see in my pseudo-code (https://gafferongames.com/post/integration\_basics/). But this doesn't give 100% accurate jump height. Everyone tells me to implement RK4 and/or make dt as small as possible. Neither of these things is necessary. While it would be great if the game could run at a consistent 60 FPS on all machines it's just not realistic.

I figured out how to achieve a consistent jump height with no downsides. First of all, you add half of the gravity before and after you move with velocity. Secondly, you need to check if adding the gravity will make the object move in the opposite y direction if so you should first move to the position where velocity.Y = 0 and then add the gravity to the velocity, so the object will move that distance in the next frame.

So how do you find the position where velocity.Y = 0? By using physical formulas.

The time from now until the object's velocity = 0

t = velocity.Y / gravity

The y-distance from here until the position where velocity.Y = 0

y = -0.5 * gravity * t^2 + velocity.Y * t

So in pseudo-code:

```
if (velocity.Y < 0 && velocity.Y + (gravity * dt) >= 0)
{
    float t = velocity.Y / gravity;
    float y = (-0.5f * gravity * (t * t)) + (velocity.Y * t);
    velocity.Y = -y;
    Move(new Vector2(velocity.X * dt, velocity.Y));
    velocity.Y += gravity * dt;
}
else
{
    velocity.Y += gravity * dt * 0.5f;
    Move(velocity * dt);
    velocity.Y += gravity * dt * 0.5f;
}

```

This might change depending on which direction is up and down for you, but this is the general gist of it and this gives me the same jump height for all frame rates.

BTW I'm using continuous collision detection, so there is no fear of tunneling or other weird side effects from low frame rates.

---
Tags: physics, jumping
---