# Question
Title: How to propagate component updates? (Changing components at runtime)
Whenever an entity is being added to an entity controller (which is essentially just a bag of entities), I scan through it's components to figure out if I need to register additional entity processors (game systems). For instance, if I add an entity which has a SpriteComponent attached to it for the first time, the EntityController resolves the e.g. SpriteRenderSystem using a factory and a simple specification, which is then being registered within the controller.

Now I'd like to make it possible to figure out whether the component of an entity has changed. I was suggested in off-topic discussion elsewhere that I should use an eventing system to raise component change events in order to have the entity rescanned.

However this has two problems, I think:

* The entity, which was a simple component bag beforehand, now holds a dependency to a event bus.
* An event bus traditionally raises global fire-and-forget events. My entitiy controllers are the base of scenes (individual game states to activate/deactivate entities together) - and there can be many scenes active at once. When a component changed event fires, then I ask myself: In which entity controller is the affected entity? Scanning all controllers for whether they contain the entity sounds expensive.

Another option would simply make the entity aware of the entity controllers in order to signal "Hey, I have changed!". However should an entity know where it's currently attached to?

# Answer
Whenever a Entity is added to a Entity Controller (EC), this EC registers to ComponentAdded and ComponentRemoved events from the Entity.

When a Component is added or removed from an Entity, fire the proper event.

The event handler of EC is called, then you can insert or remove the Entity from Systems according to the Components it has at the moment.
> 2 votes

---
Tags: c#, entity-system, entity-component, game-state, entity
---


# Question
Title: When using Unity 5, is there a way to print/save/identify the last n lines of code that were executed at a specific point?
So, here is what I am after. Is there a way to identify which were the last n lines of code that were executed in Unity 5 (with C#) at a given point of the game?

I know I can use Debug.Break() to set break points to help identifying problematic parts of the code. However, when the codes escalate and multiple functions interact, it is sometimes difficult to identify what came immediately before the break point.

Therefore, my question. Is there a way to retrieve the lines of code that were executed for instance before a break point?

# Answer
You can use the property `Environment.StackTrace` to get the current call-stack, i.e. which method called which method which called which method which called this method.

Most debuggers also expose this information in a more comfortable way.

This usually gives you a pretty good picture of what chain of events lead to this line being executed. It won't tell you which path of an if/else was taken before jumping into another method, though.
> 1 votes

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


# Question
Title: How do I correctly use SDL_RegisterEvent to create SDL_UserEvents?
I've been looking to use SDL's own event messaging system to pass events around to different parts of my game, since it supports user events.

However, the documentation isn't very clear. Here is the code snippet it gives:

```
Uint32 myEventType = SDL_RegisterEvents(1);
if (myEventType != ((Uint32)-1)) {
    SDL_Event event;
    SDL_memset(&event, 0, sizeof(event)); /* or SDL_zero(event) */
    event.type = myEventType;
    event.user.code = my_event_code;
    event.user.data1 = significant_data;
    event.user.data2 = 0;
    SDL_PushEvent(&event);
}

```

My questions:

* Does every type returned by `SDL_RegisterEvents` get read as SDL\_UserEvent? If so, why even bother registering more than one event when you can use the `event.user.code` field to differentiate between types?
* Do I need to call `SDL_RegisterEvents` each time I want to push my own event onto the event queue? Does this mean once the event I queue up is read, it trashes the type given to me by `SDL_RegisterEvent` and recycles it for another call?

The wiki is fairly vague, and there is next to nothing out there about using the `SDL_UserEvent` event type, so I am not entirely sure how to take advantage of SDLs built-in event handling system.

# Answer
> 2 votes
> Does every type returned by SDL\_RegisterEvents get read as SDL\_UserEvent? If so, why even bother registering more than one event when you can use the event.user.code field to differentiate between types?

All the event types returned by `SDL_RegisterEvents` are considered "user events", yes.

The `code` field can be used for whatever you want. Two examples:

* Register only one custom event type for your game, and use the `code` field to dispatch to code that handles the specific event. This way you consume less of the (technically) limited SDL user event ID pool (in practice this pool is in excess of 32k entries, however).
* You can't really extend the user event structure, so you have a relatively limited number of places to shove specific data related to your event. You have the 32-bit `code` field and two pointers. The pointers mean you potentially have to manage the lifetime of the data they point to somehow, which can be a chore. So you can instead use the `code` field as an index into some polymorphic array containing additional data and whatnot for your event beyond what you can fit into the storage of `SDL_UserEvent`. Again, you *could* use the pointers for this, as well, so this is just SDL giving you some options for flexibility of implementation.

> Do I need to call SDL\_RegisterEvents each time I want to push my own event onto the event queue? Does this mean once the event I queue up is read, it trashes the type given to me by SDL\_RegisterEvent and recycles it for another call?

You only need to call `SDL_RegisterEvents` once for any given event type. Once you do so, cache the returned ID (or ID range) somewhere and you can re-use it to create as many `SDL_Event`s with that type as you want.

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


# Question
Title: FileNotFoundException while using ShaderbyteCode.CompilefromFile method
I'm currently learning SlimDX, I want to load a Shader from tutorial which is named "triangle.fx" and it is in a folder called "FX",everything is in my solution. When I'm typing this line of code:

```
 using (var bytecode = ShaderBytecode.CompileFromFile(@"FX/triangle.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None))

```

I'm getting FileNotFoundException, and I don't know why because everything exists in my solution.

# Answer
> 0 votes
Make sure the FX folder is a subdirectory of the folder containing the .exe. In this case /bin/debug/FX

---
Tags: c#, slimdx
---


# Question
Title: What Is A Good Way To Make A Self Updating Game? (Python)
I've been making games and I have always had a problem if I wanted to sell a game. People would have to re-buy games to get the updated version. Does anyone have any ideas on how to make a self updating game? (In python 3.)

# Answer
Create two separate applications: Your actual game and a launcher. Configure your installer to create shortcuts for the launcher, not the actual game.

When the launcher is executed, it first goes online and checks if there is an update for your game. When there is, it downloads it and patches the copy of the actual game. A lightweight way to do this is to place a text file on your website with the current version number and a URL for the current version. Have your launcher download that small file and compare it with the current version number of your game. When it's lower, request the URL in that file.

Then have it execute the actual game.

However, most digital distribution platforms have an own launcher which can keep the users games up-to-date automatically so you don't have to worry about this. For more information if and how you can release an update with your distribution platform, consult its documentation.
> 2 votes

---
Tags: python, pygame, deployment
---


# Question
Title: How to handle GameObjects that have been destroyed but are still held by others?
I'm developing my own game engine in C++ as a learning exercise. I have employed a fairly standard method of handling destroyed GameObjects:

1. Mark them as destroyed
2. Have the scene delete destroyed GameObjects at the end of the update cycle

This is perfectly fine, however if I want a GameObject to hold a reference of another GameObject then I need to decide what happens to that now destroyed object.

At the moment I'm using `std::shared_ptr` to support multiple ownership of GameObjects so that they are held by both the scene and any other GameObjects within the game. **This means that if the scene 'destroys' them they will live on as they are still pointed to by any GameObjects still using them.** This could potentially cause strange behaviour when GameObjects no longer in the scene are still used by GameObjects in the scene.

There are alternatives involving raw pointers: where the GameObject pointing to another might start trying to use an GameObject that has actually been deleted, or `std::unique_ptr`s where GameObjects would not be able to hold a pointer to another.

Is the best strategy simply to ask the object if it has been destroyed before using it everywhere in the code base? This seems like a fairly risky way of ensuring issues don't occur.

# Answer
> 6 votes
> At the moment I'm using std::shared\_ptr to support multiple ownership of GameObjects so that they are held by both the scene and any other GameObjects within the game

Don't do that. `shared_ptr` is often the wrong tool for the job, and that certainly applies here. Remember that smart pointers are for managing ownership; `shared_ptr` is about sharing ownership. You don't want that. You want the core engine to own your game objects, not random game code.

There are various solutions here. The one built-in to C++ (in the standard library) would be `weak_ptr`, but I advise against those even more strongly than I do against `shared_ptr`.

One of the more typical approaches in game engines is to use a concept of a handle instead of a raw pointer. In a "pure" ECS, that means that you just hold on to the `Entity` (which remember, would just be an integer ID and not a pointer!). When you need to manipulate the object, you then either request a (temporary) pointer or you use an interface that takes the handle for each manipulation.

The temporary pointer approach is roughly:

```
Handle id = /*whatever*/;

Object* object = system->GetObject(id );
if (object != nullptr) {
  object->DoThings(value1, value2);
  auto x = object->DoStuff();
  object->DoUpdate(x + 1);
}

```

With such an interface, the return pointer is "temporary." That means that you can't hold on to you. You can use it for your local calculations and then must release it. This is safe because the object system will never delete or free objects until the end of the frame during a cleanup step, so even if a game object is deleted, any pointers you've acquired are good.

You can take that a step further and have `GetObject` return a smart pointer (e.g. a `shared_ptr` in the simplest case) that "pins" the object in memory while the pointer is in use but allows it to be immediately cleaned up after release. That can be useful if you have a coroutine-based scripting language where some event callback function might be handled across frame boundaries as you don't want scripters to have to deal with pointer validity or object lifetimes. You might be best off using the system/id approach for all script function implementations, though.

```
Handle id = /*whatever*/;

pin<Object> object = system->PinObject(id);

if (object) {
  object->DoThings(value1, value2);
  auto x = object->DoStuff();
  object->DoUpdate(x + 1);
}

```

The other approach is to not actually have a publicly available class for your game objects and instead require all manipulation of objects to go through the owning system. The system is then free to manipulate the data structures holding the objects however and whenever it pleases, because nobody external to the system ever has a pointer directly to any internal object. This is an essential interface design technique for data-oriented design (there's more to it, of course).

```
Handle id = /*whatever*/;

system->DoThings(id, value1, value 2);
auto x = system->DoStuff(id); // returns a "default" value if the id is invalid/dead
system->DoUpdate(id, x + 1);

```

# Answer
> 1 votes
I see a couple of options:

1. Have the `Scene` refuse to destroy a `GameObject` if the ref\_count of it's `shared_ptr` is more than 1. This will oblige your users to take a great care of what happens. This might not be very fun or practical, though.
2. In your `GameObject` architecture, add a listener pattern: when `GameObject` A links to `GameObject` B, tell B that A is linked to it. So when `GameObject` B is destroyed, notify all the other linked `GameObject`s (A) that B has been destroyed and so delete the link.
3. Don't link your `GameObject`s together. Keep some kind of reference to the game object that you need instead, and fetch it each frame from the `Scene`. If the `GameObject` it's destroyed, the `Scene` will return `nullptr`, and you'll know that the other object is dead. Your vector could then contain `unique_ptr` instead of `shared_ptr`.

# Answer
> 1 votes
One possible solution could be to use `weak_ptr`.

A `weak_ptr` is like a `shared_ptr`, except it doesn't keep the object alive. If there are no `shared_ptr`s pointing to the object, it will be deleted, and then any `weak_ptr`s will hold NULL. You can use the `lock` method to get a `shared_ptr` from a `weak_ptr`.

Example use:

```
shared_ptr<Thingy> s = make_shared<Thingy>();
// Convert a shared_ptr to a weak_ptr
weak_ptr<Thingy> w = s;
// Convert a weak_ptr to a shared_ptr
shared_ptr<Thingy> s2 = w.lock();
// s, w and s2 point to the object, of course.

s.reset();
// s is a null pointer, w and s2 point to the object

s2.reset(); // deletes the object
// s and s2 are all null pointers now.
// w is also a null pointer (magically!)

shared_ptr<Thingy> s3 = w.lock();
// s3 is also a null pointer

```

Note that this might not completely eliminate your problem, as the object will still not be destroyed as long as there's a `shared_ptr` referring to it.

---
Tags: c++, entity-system, gameobject
---


# Question
Title: Adjust Aim Angle for Motion with Accelerating Bullet
So, here's my problem:

I have a turret attached to a ship that moves at a variable speed through my game world, shooting at the centre of another ship travelling through the game world in a possibly different vector. Currently, I get the angle that I need to shoot at using atan2:

```
double targetAngle = Math.Atan2(ship.CurrentTarget.Position.Y - ship.Position.Y, ship.CurrentTarget.Position.X - ship.Position.X);

```

This works fine when both ships are stationary, or moving very slowly, but if moving faster, the aim lags behind. An additional fun part of the puzzle: the bullet's vector isn't static, they start at 0 and increase in speed. Their position is calculated as follows:

```
var direction = new Vector2((float)Math.Cos(currentRotation),
                (float)Math.Sin(currentRotation));

            if (direction.Length() > 0)
                direction.Normalize();

            var velocity = new Vector2(direction.X * MotionData.CurrentSpeed,
                direction.Y * MotionData.CurrentSpeed) + additiveVector;

```

Where additiveVector is my ship's vector at the point the projectile was launched. CurrentSpeed will be added to every frame until it hits a static maxspeed.

So far, the problems I've encountered with other solutions for compensating my aim is that the formulas rely on a static velocity for the projectile, and mine isn't.

# Answer
Your main problem is that you have two objects (ships) and they move with different speeds and a third object that speeds up over time and you want to know the point where you have to aim to hit the ship. With this question you get the same question like military programmers - and you have a lot of variables and never a 100% chance to know the real point.

You break it to just the moving part and not include wind, waves and so on - that makes it easier but not easy.^^

You have 5 variables in this formula:

* **ship-angles** (2) the angle of each ship can change(?) - if they start a turn
* **ship-speeds** (2) the speed of each ship increases to a maximum
* **bullet-speed** (1) the speed of the bullet increases over time

The first effect the possible positions to hit the other ship, the last is important to know how long does the bullet fly over the given distance and how this time has to change the angle.

To solve this you have two ways, I know:

## 1. Table

The first solution could be something like a table/matrix where you define multiple value pairs and look up with the current ones how your angle should be - this will result in a lower chance to hit the other ship but is fast.

## 2. Calculation

The second is, like you tried it, a complex formula to calculate with all parameters the correct aim point.

Some ideas for this:

1. get the current distance between the two ships and the time your bullet needs
2. calculate the speed difference of both ships to know if you or the other ship will be ahead in the time of step 1 - with this info you know if you have to adjust the angle positive or negative and you know, cause of the time of step 1, how much meters the difference will be
3. get the angle between the two ships - if they are not parallel you have to adjust the distance your bullet have to fly cause the other ship comes closer or further to you

With these infos you should have all parameters solved your calculation needs - with these infos you can get the coordinate of the other ship if your bullet should hit. And then you can calculate the angle for your turret/bullet to the provided coordinates and not the current position of the ship.
> 1 votes

# Answer
To expand on (*one way you could do*) the mathematics behind @Gummibeer's answer..

Keep in mind this physics calculation

> d = vt + 1/2at2
> or
> distance = initialVelocity\*time + 1/2 acceleration * time2

Say your turret is at \[0,0\] and the enemy is at \[10,0\] and..
Say your bullet starts at 0 velocity, and accelerates at 1 unit/sec/sec

If we aim at where the enemy was, the `totalDistance` is 10 units. Lets also say that our `acceleration` is a simple 1 \[unit\] per second, per second. (*One important note is to keep all distances and all time frames on the same scale*)

> 10 = 0\*time + 1/2 1 * time2 ...
> 10 = 1/2 * time2...
> 20 = time2
> time = 4.4721359 seconds

So, we now know that the target has that amount of time to change their position. There are numerous strategies you could use to go about guessing where they would move to in that period of time. The simplest would be to take their current velocity, assume they will continue at that velocity, and recalculate to that new position.

However, note that there is a paradox here which prevents you from finding the exact time and position of collision with the target, though you can get very close. By recalculating at their new position, there will be a change in the time calculation, which means you could recalculate to their adjusted position after that, and after that, and after that - each iteration getting more and more precise, but never reaching complete 100% accuracy. This is one of Zeno's paradoxes - Achilles and the tortoise.
> 0 votes

---
Tags: mathematics, xna-4.0, projectile-physics
---


title: How to fix my camera collision, C# XNA

text:
# Question
Title: How to fix my camera collision, C# XNA
I am having some weird issues with my camera. I am trying to make it so it is a first person camera, that when the user presses the W or Up key, it moves towards where the camera is looking. My issue is i can either have it working like that, but no collision working, I did a little debugging and the players world wasn't aligned with the camera even after changing them manually to be such. Or the other method, has collision but the camera doesn't go to where its facing, but just along the X and Z axis.

here is my camera class (The previewMove is meant to check for bounding spheres? I just dont know how i'd do that really):

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Game7
{
    class Camera : GameComponent
    {
        public Vector3 cameraPosition;
        private Vector3 cameraRotation;
        private float cameraSpeed;
        private Vector3 cameraLookAt;

        private Vector3 mouseRotationBuffer;
        private MouseState currentMouseState;
        private MouseState previousMouseState;

        // Properties

        public Vector3 Position
        {
            get { return cameraPosition; }
            set
            {
                cameraPosition = value;
                UpdateLookAt();
            }
        }

        public Vector3 Rotation
        {
            get { return cameraRotation; }
            set
            {
                cameraRotation = value;
                UpdateLookAt();
            }
        }

        public Matrix Projection
        {
            get;
            protected set;
        }

        public Matrix View
        {

            get
            {
                return Matrix.CreateLookAt(cameraPosition, cameraLookAt, Vector3.Up);
            }
        }

        //Constructor
        public Camera(Game game, Vector3 position, Vector3 rotation, float speed)
            : base(game)
        {
            cameraSpeed = speed;

            // projection matrix
            Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                Game.GraphicsDevice.Viewport.AspectRatio,
                0.05f,
                1000.0f);

            // set camera positiona nd rotation
            MoveTo(position, rotation);

            previousMouseState = Mouse.GetState();
        }

        // set Camera's position and rotation
        private void MoveTo(Vector3 pos, Vector3 rot)
        {
            Position = pos;
            Rotation = rot;
        }

        //update the look at vector
        private void UpdateLookAt()
        {
            // build rotation matrix
            Matrix rotationMatrix = Matrix.CreateRotationX(cameraRotation.X) * Matrix.CreateRotationY(cameraRotation.Y);
            // Look at ofset, change of look at
            Vector3 lookAtOffset = Vector3.Transform(Vector3.UnitZ, rotationMatrix);
            // update our cameras look at vector
            cameraLookAt = cameraPosition + lookAtOffset;
        }

        // Simulated movement
        public Vector3 PreviewMove(Vector3 amount)
        {
                // Create rotate matrix
                Matrix rotate = Matrix.CreateRotationY(cameraRotation.Y);
                // Create a movement vector
                Vector3 movement = new Vector3(amount.X, amount.Y, amount.Z);
                movement = Vector3.Transform(movement, rotate);

                return cameraPosition + movement;
        }

        // Actually move the camera
        private void Move(Vector3 scale)
        {
            MoveTo(PreviewMove(scale), Rotation);
        }

        // updat method
        public override void Update(GameTime gameTime)
        {
            // smooth mouse?
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;

            currentMouseState = Mouse.GetState();

            KeyboardState ks = Keyboard.GetState();

            // input

            Vector3 moveVector = Vector3.Zero;

            if (ks.IsKeyDown(Keys.W))
                moveVector.Z = 1;
            if (ks.IsKeyDown(Keys.S))
                moveVector.Z = -1;
            if (ks.IsKeyDown(Keys.A))
                moveVector.X = 1;
            if (ks.IsKeyDown(Keys.D))
                moveVector.X = -1;

            if (moveVector != Vector3.Zero)
            {
                //normalize it
                //so that we dont move faster diagonally
                moveVector.Normalize();
                // now smooth and speed
                moveVector *= dt * cameraSpeed;
                // move camera
                Move(moveVector);
            }

            // Handle mouse input

            float deltaX;
            float deltaY;

            if(currentMouseState != previousMouseState)
            {
                //Cache mouse location
                deltaX = currentMouseState.X - (Game.GraphicsDevice.Viewport.Width / 2);
                deltaY = currentMouseState.Y - (Game.GraphicsDevice.Viewport.Height / 2);

                // smooth mouse ? rotation
                mouseRotationBuffer.X -= 0.01f * deltaX * dt;
                mouseRotationBuffer.Y -= 0.01f * deltaY * dt;

                if (mouseRotationBuffer.Y < MathHelper.ToRadians(-75.0f))
                    mouseRotationBuffer.Y = mouseRotationBuffer.Y - (mouseRotationBuffer.Y - MathHelper.ToRadians(-75.0f));
                if (mouseRotationBuffer.Y > MathHelper.ToRadians(75.0f))
                    mouseRotationBuffer.Y = mouseRotationBuffer.Y - (mouseRotationBuffer.Y - MathHelper.ToRadians(75.0f));

                Rotation = new Vector3(-MathHelper.Clamp(mouseRotationBuffer.Y, MathHelper.ToRadians(-75.0f), MathHelper.ToRadians(75.0f)), MathHelper.WrapAngle(mouseRotationBuffer.X), 0);

                deltaX = 0;
                deltaY = 0;

            }

            // Alt + F4 to close now.
            // Makes sure the mouse doesn't wander across the screen (might be a little buggy by showing the mouse)
            Mouse.SetPosition(Game.GraphicsDevice.Viewport.Width / 2, Game.GraphicsDevice.Viewport.Height / 2);

            previousMouseState = currentMouseState;

                base.Update(gameTime);
        }

    }
}

```

And here is how i am building the camera and controlling it in my game1.cs:

```
camera = new Camera(this, new Vector3(player_x, player_y, player_z), Vector3.Zero, 5f);
            Components.Add(camera);

if (kb.IsKeyDown(Keys.Up))
                {
                    player_z = player_z + 0.05f;
                    world_player = Matrix.CreateTranslation(new Vector3(player_x, player_y, player_z));
                    // use this code for any standard collision
                    if ((IsCollision(ball, world_player, ball, world_cannon)) || (IsCollision(ball, world_player, ball, walls[0])) || (IsCollision(ball, world_player, ball, walls[1])) || (IsCollision(ball, world_player, ball, walls[2])) || (IsCollision(ball, world_player, ball, walls[3])) || (IsCollision(ball, world_player, ball, walls[4])) || (IsCollision(ball, world_player, ball, walls[5])))
                    {
                        player_z = player_z - 0.05f;
                        //camera.Position = new Vector3(player_x, player_y, player_z);
                        world_player = Matrix.CreateTranslation(player_x, player_y, player_z);
                    }
                }
                if (kb.IsKeyDown(Keys.Down))
                {
                    player_z = player_z - 0.05f;
                    world_player = Matrix.CreateTranslation(new Vector3(player_x, player_y, player_z));
                    // use this code for any standard collision
                    if ((IsCollision(ball, world_player, ball, world_cannon)) || (IsCollision(ball, world_player, ball, walls[0])) || (IsCollision(ball, world_player, ball, walls[1])) || (IsCollision(ball, world_player, ball, walls[2])) || (IsCollision(ball, world_player, ball, walls[3])) || (IsCollision(ball, world_player, ball, walls[4])) || (IsCollision(ball, world_player, ball, walls[5])))
                    {
                        player_z = player_z + 0.05f;
                        world_player = Matrix.CreateTranslation(new Vector3(player_x, player_y, player_z));
                    }
                }

                // this makes it first person with collision but bad movement
                //camera.Position = new Vector3(player_x, player_y, player_z);

                // this makes it a better first person movement but no collision.
                //world_player = Matrix.CreateTranslation(camera.Position);

```

Thank you for any help, i really am at a loss currently with this.

# Answer
> -1 votes
XNA has a Vector3.Forward, transform that with your cameras viewmatrix and if necessary set your y component to zero and normalize.

Generally if this gives you trouble you should refresh your basic understanding of linear algebra.

---
Tags: xna, 3d, camera, monogame, first-person-shooter
---


title: WebGL - Open URL in new tab?

text:
# Question
Title: WebGL - Open URL in new tab?
How to open URL in new tab for WebGL?

Tried Application.OpenURL("url"). But it's opens a tab in same window

Thanks

# Answer
> 0 votes
You can't. You don't have any way to set the target attribute from within the player. The docs for the OpenURL state

> When executed in the web player, the page the plugin is contained in will be redirected to the url.

I would just assume that it's also true for the webGL player.

But if you took the time to read the maunual, you could write a simple javascript to open new tabs, and call that from the webGL player.

Your probably getting down voted because this info is readily available.

---
Tags: unity, webgl, browser-based-games, browser
---


# Question
Title: Publishing a game on Steam without going throught Greenlight
Is there any possible way to publish a game on Steam without going through Steam Greenlight?

# Answer
> 4 votes
If you are already on Steam as a publisher, then you can post other games after a short evaluation by them.

In the past (before Greenlight) you could enter by personally asking them. A contract was custom made for you and off you went.

Once Greenlight started, that option ceased to exist and the only way to accept new publishers is that option.

---
Tags: publishing, steam
---


# Question
Title: (Pygame) Sprite disappearing on collision
I am making a game, and when the player runs into a certain block it changes the size of a circle on the top. The problem is, whenever the player runs into the block it disappears. How can I fix this?

# Answer
What most likely happens from the (very basic and incomplete) description of your issue is that each frame you detect a collision, you reduce the size of the shape. Thus, frame after frame the shape gets smaller and smaller, so much that it's no longer visible.

When you get the collision and you change the size of the shape, you also have to set a flag to tell it to not do it again the following frames. You reset the flag once there is no longer any collision detected.
> 1 votes

# Answer
It's hard to know what's happening without seeing example code but it could be the order with which you erase and draw the sprites. For example, if you had the following steps:

1. Erase circle
2. Draw smaller circle
3. Erase player \<-- this is where you might be erasing the smaller circle
4. Draw player

If the above is your problem, the fix would be to erase everything, then draw everything in the order you want (e.g. correct layering).
> 0 votes

---
Tags: pygame
---


# Question
Title: Can't call GameCenter in my Unity game for iOS
I'm trying to integrate Game Center into my Unity 5 project and facings troubles. It seems that authentification is OK when the game starts on iOS device, a notification appears, but leaderboard button does not work, nothing happens when I tap GC button. I assigned the initiation of "ShowLeaderboard()" to GC button. Please, take a look at the script I use below. Hope to find a resolution for my issue. Thank you in advance.

```
using UnityEngine;
using UnityEngine.SocialPlatforms;
using UnityEngine.SocialPlatforms.GameCenter;
using System.Collections;

public class GameCenter : MonoBehaviour {

    public string leaderboardID = "mygameleaderboard";

    void Start () {
        AuthenticateToGameCenter();
    }

    private bool isAuthenticatedToGameCenter;
    public static void  AuthenticateToGameCenter() {
        #if UNITY_IPHONE
        Social.localUser.Authenticate(success => {
        if (success) {
            Debug.Log("Authentication successful");
        } else {
            Debug.Log("Authentication failed");
            }
        });
        #endif
    }

    public static void ReportScore(long score, string leaderboardID) {
        #if UNITY_IPHONE
        Debug.Log("Reporting score " + score + " on leaderboard " + leaderboardID);
        Social.ReportScore(score, leaderboardID, success => {
            if (success) {
            Debug.Log("Reported score successfully");
            } else {
                Debug.Log("Failed to report score");
                }
            });
        #endif
    }

    //call to show leaderboard
    public static void ShowLeaderboard() {
        #if UNITY_IPHONE
        Social.ShowLeaderboardUI();
        #endif
    }
}

```

# Answer
Double check in your itunes account if you have added leaderboard id in your version. Like,
> 1 votes

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


# Question
Title: Java creating random pipes from an image
Im trying to make a simple clone of flappy bird game. The tutorial that i watched used only rectangles for all the objects. But the thing is im trying to do it with nicer images. I have handled the bird and its movements but i can not generate pipes from images and terminate them after they get out of the screen.

The way i want to do is just like the tutorial. He made an arraylist of rectangles, and simply adding rectangles to that list with the position and dimension variables. When they go out of the screen, he deletes the pipes and add the new ones with "arraylist.add(new Rectangle())", and simply draws them with Graphics.fillRect(). But i cant do it with BufferedImage type or neither the Graphics2D.

Could anyone help please? I want to be able to generate random pipes like rectangles, and wanna be able to add them to an arraylist and draw them. Its pretty like creating blocks from an image in mario game

Any help would be appreciated!

# Answer
I assume your are using 'java.awt.\*' to do this and you wanted this solution to be similar in nature. In that case I think the easiest solution would be to simply be extending the Rectangle class with a field for your BufferedImage and draw using that.

RectangleImage.java:

```
import java.awt.Rectangle;
import java.awt.image.BufferedImage;

public class RectangleImage extends Rectangle {

    public BufferedImage img;

    public RectangleImage(BufferedImage img, int x, int y) {
        this.x = x;
        this.y = y;
        this.img = img;
        this.width = img.getWidth();
        this.height = img.getHeight();
    }
}

```

This is a rectangle that contains an image and is as wide and as tall as the image and can be rendered out as any other rectangle by using `fillRect()` as usual. However if you want to render it out as an image, then you simply use `drawImage()` instead.

Example:

```
RectangleImage recImg = new RectangleImage(null, 0, 0);
Graphics.drawImage(recImg.img, recImg.x, recImg.y, recImg.width, recImg.height, null);

```
> 1 votes

---
Tags: java, graphics
---


# Question
Title: Help with drawing a polygon with N sides
***I am at university on my games development, and I have been given work to fill in an empty pixel plotter program using the methods they have supplied for it to teach us the algorithms used in 2 dimensional games.***

I am currently trying to draw a polygon of N Sides using a function called void `PixelPlotterForm::DrawPolygon( int Sides, int X, int Y, int R, Color PixelColour )` which we have been given the parameter but not the algorithm.

Here is my attempt so far:

```
void PixelPlotterForm::DrawPolygon( int Sides, int X, int Y, int R, Color PixelColour )
{
    // Fill in the correct code here
    int x = 0;
    int y = 0;
    //float currentr = 360 / Sides;
    int n = 0;
    int r = R;
    for (n = 0; n < Sides; n++)
    {
        x = r * cos(2 * PI*n / Sides) + X;
        y = r * sin(2 * PI* n / Sides) + Y;
        SetViewportPixel(x, y, PixelColour); // this is where the function is called
      // and the pixel is set from this.
    }

}

```

Currently the code does not work as desired, at the moment I have only reached drawing all 4 points, but something when drawing the polygon makes the points go skew-wif so to speak.

The left image is the trace that is drawn as a bounding box from the mouse, dragging it makes it larger like any image editing software, but the result is on the right, seems to set the angle off somehow, not sure why as the point should correlate to the trace.  \<\<-- This image shows the actual result.

**I am also of course required to draw the outline of the polygon, so I assume that I should store in a cycle of points to create a triangle so I can draw the hypotenuse, but I am unsure how to do this.**

Any help would be appreciated.

NOTE: unfortunately the code for the trace is hidden, I've searched the whole program so I don't unfortunately know how that works.

# Answer
> 2 votes
I understand you also had problems drawing a line from point to point. I recommend you look into "Bresenham's Line Algorithm" as it typically gives the best result. Here is a Wikipedia article about it.

The article includes pseudocode for the algorithm, including one that only relies on integer arithmetic. I won't be posting it here as I encourage you to actually read it. Once you have it working it should only be a matter of cycling through the points drawing lines between them. Hopefully this helps.

# Answer
> 1 votes
You're not getting the angles properly, the sum of the internal angle of a simple polygon can be calculated with the formula: *π(n-2)*.

We then need the external angle which is the angle from point to point, this can be calculated with : *π-internalAngle*.

Assuming the first point is in the lower left and there's no rotation this code should work.

```
void PixelPlotterForm::DrawPolygon( int Sides, int X, int Y, int R, Color PixelColour )
        {
            // Fill in the correct code here
            int x = X;
            int y = Y;
            internalAngle = PI * (Sides-2) / Sides;
            externalAngle = PI - internalAngle
            for (int n = 0; n < Sides; n++)
            {
                x += R * cos(externalAngle * n);
                y += R * sin(externalAngle * n);
                SetViewportPixel(x, y, PixelColour); // this is where the function is called
              // and the pixel is set from this.
            }
         }

```

---
Tags: 2d, algorithm, geometry
---


title: equirectangular panorama rendering?

text:
# Question
Title: equirectangular panorama rendering?
I want to render my scenes as equirectangular panorama frames.

I can get the angular fisheye which is what I actually need by applying the rendered frame as a texture to a correctly UV mapped circle.

But how can the scene be rendered as equirectangular panorama?

I'm using a 3d engine which uses OpenGL and GLSL.

# Answer
> 2 votes
You would have to render your scene into a cube map, then render a quad. The texture coordinates would then translate directly to longitude/latitude you can use to calculate the vector to use for sampling the cube map.

For equirectangular projection:

```
lon = u*2*pi
lat = (v*2-1)*2*pi

x = cos(lon)*cos(lat)
y = sin(lon)*cos(lat)
z = sin(lat)

```

Where u/v are the texture coordinates of the quad.

---
Tags: opengl, rendering, glsl, camera, fragment-shader
---


# Question
Title: What is the semantic meaning of the position of Unity's transform component?
What is the meaning of the position in a transform component of a game object in Unity? Is it the center of mass?

# Answer
> 2 votes
It is the Anchor point. The anchor point is defined by the asset. I believe the default anchor point for 3D assets is the center of gravity. For a 2D object, it is the center of the box.

Note that the anchor point defines the rotation, so that might be important in determining how things work.

It's worth noting that you can change the center of mass from the default, as is shown in the Unity documentation. A rigidbody has a center of mass that can be changed by scripting to better match your requirements.

---
Tags: unity
---


# Question
Title: Using Unity built-in sprites programatically
I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together.

```
panelImage.sprite = UnityEditor.AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/InputFieldBackground.psd");
panelImage.sprite = Resources.GetBuiltinResource(typeof(Sprite), "Resources/unity_builtin_extra/Background.psd") as Sprite;

```

The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?

# Answer
This isn't recommended practice at all. While there are ways to use built in resources, the images aren't defined, and might have issues if you choose to use them.

What a much better way to do it, and the way that I have done, is to have a prefab defined using the desired format, and instantiate it, rather than attempt to do this all programmatically.
> 1 votes

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


title: Unity camera tilt

text:
# Question
Title: Unity camera tilt
I'm programming a camera for an RTS and I'm stuck on tilting the camera up and down.

I want the camera to tilt between 20 and 70 degrees using the Z and X keys. This is my code:

```
using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

    //Variables to alter or track in Unity
    public float scrollSpeed;
    public float increasedScroll;
    public float scrollEdge;
    public float panSpeed;
    public float increasedPan;
    public float rotateSpeed;
    public float currentZoom;
    public float zoomSpeed;
    public float zoomRotation;
    public Vector2 zoomRange;
    public float tiltAngle;
    public Vector2 tiltAngleRange;

    //Variables for use in script
    private Vector3 initialPosition;
    private Quaternion initialRotation;
    private Vector3 mouse;

    //
    void Start()
    {
        initialPosition = transform.position;
        initialRotation = transform.rotation;
    }

    //Each frame
    void Update()
    {
        //BASIC CAMERA MOVEMENT (panning)

        //Check for shift key input and change speed accordingly
        shiftSpeed(increasedPan, increasedScroll);

        //Pan with middle mouse
        mouse = Input.mousePosition;
        if (Input.GetKey("mouse 2"))
        {
            panMove(Vector3.right, mouse.x, Screen.width);
            panMove(Vector3.forward, mouse.y, Screen.height);
        }
        //Pan with WASD keys or edge of screen
        else
        {
            if(Input.GetKey("d") || mouse.x >= Screen.width * (1 - scrollEdge))
            {
                moveCamera(Vector3.right, scrollSpeed);
            }
            else if (Input.GetKey("a") || mouse.x <= Screen.width * scrollEdge)
            {
                moveCamera(Vector3.right, -scrollSpeed);
            }
            if (Input.GetKey("w") || mouse.y >= Screen.height * (1 - scrollEdge))
            {
                moveCamera(Vector3.forward, scrollSpeed);
            }
            else if (Input.GetKey("s") || mouse.y <= Screen.width * scrollEdge)
            {
                moveCamera(Vector3.forward, -scrollSpeed);
            }
        }

        //Camera zoom with scrl wheel (up and down)
        currentZoom -= Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * 1000 * zoomSpeed;
        currentZoom = Mathf.Clamp(currentZoom, zoomRange.x, zoomRange.y);
        transform.position = new Vector3(transform.position.x, transform.position.y - (transform.position.y - (initialPosition.y + currentZoom)) * 0.1f, transform.position.z);

        //Camera tilt with ZX keys
        if (Input.GetKey("z"))
        {
            tiltCamera(tiltAngle);
        }
        else if (Input.GetKey("x"))
        {
            tiltCamera(-tiltAngle);
        }

    }

    //Occurs after update
    void LateUpdate()
    {
        //Remove shifted spped
        shiftSpeed(-increasedPan, -increasedScroll);
    }

    void shiftSpeed(float panChange, float scrollChange)
    {
        if (Input.GetKey(KeyCode.LeftShift))
        {
            panSpeed += panChange;
            scrollSpeed += scrollChange;
        }
    }

    void panMove(Vector3 panDirection, float inputDirection, int screenAxis)
    {
        moveCamera(panDirection, panSpeed * ((inputDirection - screenAxis * 0.5f) / (screenAxis * 0.5f)));
    }

    void moveCamera(Vector3 direction, float scrlOrPanSpeed)
    {
        transform.Translate(direction * Time.deltaTime * scrlOrPanSpeed, Space.World);
    }

    void tiltCamera(float angle)
    {
        angle = angle + initialRotation.eulerAngles.x;
        Quaternion newRotation = Quaternion.AngleAxis(angle, Vector3.left);
        transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, 1f);
    }
}

```

At the moment it just tilts up or down by 1 degree from the starting rotation when I press Z and X.

# Answer
Well, to achieve your requirement, I have another work around, place these lines of code in very same script.

```
...

public float _cameraRotationSpeed = 0.1f;

...
void Update ()
    {
        ...
        ...

        if (Input.GetKey ("z")) {
            tiltCamera (true); // Replace parameter with bool
        } else if (Input.GetKey ("x")) {
            tiltCamera (false); // Replace parameter with bool
        }

        ...
        ...
    }

// Replace your tilt camera method by

void tiltCamera (bool rotateRight)
    {
        // Y represents rotation around Y-axis and will rotate in x-z axes. You can modify it.

        float angle = transform.eulerAngles.y;
        if (rotateRight)
            angle += _cameraRotationSpeed;
        else
            angle -= _cameraRotationSpeed;
        angle = Mathf.Clamp (angle, 20, 70);

        // Whatever reference you got in angle change exactly that same axis. For now Y rotation is being changed.
        transform.eulerAngles = new Vector3 (transform.eulerAngles.x, angle, transform.eulerAngles.z);
    }
...

```
> 2 votes

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


# Question
Title: Why do SDL_Textures need to be created with a renderer?
I know how to create textures in SDL, but I don't get why they need to be created with a renderer: `SDL_CreateTexture(SDL_Renderer* renderer, ...)`

When it comes to rendering, I can render my texture on every renderer, regardless from which renderer it was created on. Then why does `SDL_CreateTexture` require me to pass in a renderer?

# Answer
`SDL_Renderer` is an abstraction over some concept in the underlying graphics API. In OpenGL that concept is the *context* and in D3D it's the *device*. In these underlying graphics APIs, creating textures is an operation you do from a context or device, and so the SDL abstractions over those APIs *must* carry forward that relationship (or weaken the API).

Why do the underlying graphics APIs work that way? Because the context or the device is sortof like a representation of the graphics card itself, and the graphics card will be where most of the important texture data actually lives, and thus creating textures has to be done via the interface to the graphics card.
> 2 votes

# Answer
This is the data I could gather from a quick glimpse at the SDL's source code.

Firstly, the renderer stores the driver data, and the maximum texture size depends on the driver/GPU, so firstly in `SDL_CreateTexture` the code makes sure that the wanted texture isn't too big.

Then the code splits into platform/rendering API specific code. As Alexandre Vaillancourt said in the comments, the renderer stores the OpenGL context data that is required for creating the texture.

I'm also pretty sure that you can also force `SDL_Renderer` to use a specific rendering API at least in some hacky way, and rendering textures that are created on a DirectX renderer sure won't work with an OpenGL-based renderer.

Lastly, as mentioned here, the renderer also manages its textures lifetime.
> 4 votes

---
Tags: sdl2
---


# Question
Title: Is there a difference between analytics and telemetry?
We are developing a mobile game (using Unity3D). We report various game analytics events to our backend systems so they can be aggregated and analyzed later on.

I've recently watched this session from GDC on game telemetry: http://www.gdcvault.com/play/1012227/Development-Telemetry-in-Video-Games

I was wondering whether telemetry and analytics were in fact the same thing? They seem to be related to one another, although may have different use cases...

# Answer
Strictly, they're just words.

*Telemetry* is the act of gathering data remotely from your game:

> Telemetry is an automated communications process by which measurements are made and other data collected at remote or inaccessible points and transmitted to receiving equipment for monitoring. The word is derived from Greek roots: tele = remote, and metron = measure.

Analytics is the search for patterns in the data that you've gathered:

> Analytics is the discovery and communication of meaningful patterns in data. Especially valuable in areas rich with recorded information, analytics relies on the simultaneous application of statistics, computer programming and operations research to quantify performance. Analytics often favors data visualization to communicate insight.

Software packages tend to provide one or the other (or some combination of both), but also tend to use the terminology interchangeably if it's for marketing or branding purposes. In other words, just because a product uses the term "analytics" in its name doesn't mean it *only* provides analysis, it may also provide a mechanism or hooks for gathering the source telemetry as well.

You probably wouldn't confuse anybody if you interchange the terms now and then, as they're broadly understood to be fairly related to eachother.
> 5 votes

---
Tags: terminology, analytics, telemetry
---


title: MMO pricing model

text:
# Question
Title: MMO pricing model
How do companies that have a monthly subscription come up with what the monthly price will be? For example Blizzard worked on WoW for many years and then came up with $15/mo. What all goes into figuring out such a price point for a monthly sub? This isn't just for games but I guess would be for any software product. There is clearly a cost of maintenance (servers, support ppl, etc) but how to you quantify the initial dev cost into that monthly price?

# Answer
The question is "how much are your customers willing to pay"? This depends on how your game compares to the current competition. Players usually don't pay more than one subscription at a time, so you can only demand more than the average market rate when your game is objectively better. This consumer behavior is quite different than with one-time-payment titles where players owning very similar games often makes them more likely than less likely to also buy yours.

When World of Warcraft was released, the usual monthly subscription rate for an MMORPG was $9.99. Also, many did not require an initial investment. However, WoW had a level of quality and quantity which was obviously far higher than that of any existing MMOs. It wasn't the first on the market, but it was the first MMO you could seriously consider a triple-A title. It was undeniable that it definitely set the bar far higher. Demanding $15 per month AND a retail price was a bold move, but it objectively *was* more ambitious than anything else on the market, so people were willing to pay. And as history tells, it worked.

To find the right price for *your* game, you need to do some market research and estimate:

* How many people you can reach with your marketing campaign?
* How many of these people would be willing to play your game for what price per month. Maybe you could get 10.000 subscribers for $10 but 30.000 subscribers for $5? That's what you need to find out.
* What operational cost do you have per player (server cost, moderation, support, bookkeeping etc.)?

Then pick the price where `customers * (price - cost)` is the highest. Then check if it covers your initial development cost and development cost for future content. If not, consider a different project.
> 3 votes

---
Tags: mmo, project-management, pricing
---


# Question
Title: Bullet Physics: Difference between Motion State and World Transform
In Bullet Physics, when I create a new btRigidBody, one of the parameters passed to the constructor is the btMotionState, which defines the initial pose of the body. However, if I then later want to change the pose of the body manually (for example, if it is a kinematic body), how can I do this?

What I have tried so far, is to use the body's setWorldTransform() function. For example:

```
glm::mat4 pose;
pose[3][0] = 0.5;
pose[3][1] = 2.0;
pose[3][2] = 1.0;
btTransform new_transform;
new_transform.setFromOpenGLMatrix((float*)&pose[0]);
my_body->setWorldTransform(new_transform);

```

However, when I then try to read the pose of the object again:

```
btTransform trans = my_body->getWorldTransform();
std::cout << "Y = " << trans.getOrigin().getY() << std::endl;

```

It returns the value set in the body's constructor, not the value set in setWorldTransform().

Please can somebody explain the different between the motion state, and the world transform, and how I should go about manually updating the pose of a kinematic object?

# Answer
> 1 votes
I guess you are using the initial world transformation of the body. you should get the current motionState transformation of the body to get the current position. Also make sure you are not stepping the dynamicworld or you will get the values after applying physics.

I am usually using the below trick:

Instead of using `my_body->getWorldTransform()`, try using the below code:

```
btTransform trans;
my_body->getMotionState()->getWorldTransform(trans);
float matrix[16] ;
trans.getOpenGLMatrix(matrix);

```

---
Tags: physics, bullet-physics, physics-engine
---


# Question
Title: Can I make this physics simulation any faster?
I've made a little real time physics simulation that solves some bodies. CirclevCircle && CirclevOrientedRect I would like someone to tell me if I'm doing something drastically wrong. I know of ways to optimize this solution that require more programming. But so far is there anything I'm doing that could ruin my performance.

```
    private void Simulate(float dt)
    {
        for (int i = 0; i < physObj.Count; i++)
        {
            List<Vector2> force = new List<Vector2>();

            // Physics Objects
            if (gravity)
            {
                for (int j = 0; j < physObj.Count && j != i; j++)
                {
                    if (physObj[j].G != 0f)
                    {
                        // Calc radius between two objects
                        float r = Vector2.Distance(physObj[i].Center, physObj[j].Center);
                        // Calc components of the radius
                        Vector2 rVec = physObj[j].Center - physObj[i].Center;
                        // Calc direction based on components
                        float theta = (float)Math.Atan2(rVec.Y, rVec.X);
                        // Calc magnitude of the force of gravity Fg = G(m1m2 / r^2)
                        float mfG = physObj[j].G * (physObj[i].M * physObj[j].M / (r * r));
                        // Calc components of force of gravity using direction
                        Vector2 fGDir = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));
                        force.Add(fGDir * mfG);
                    }
                }
            }

            // Sum Forces
            for (int j = 0; j < force.Count; j++)
                physObj[i].ApplyForce(force[j]);
        }

        // Test Collisions
        if(check)
            CheckCollision();

        // Resolve Collisions
        if(resolve)
            HandleCollision();

        // Update Velocity and Position
        for (int i = 0; i < physObj.Count; i++)
        {
            // Update Velocity
            physObj[i].UpdateVelocity(dt);

            physObj[i].ResetForces();

            // Update Position
            physObj[i].UpdatePos(dt);
        }
    }

```

So here is were it checks collisions and puts them all into a list. I keep two lists of collision data. Current and previous touch. That way in the user code you can check if a collision has begun by using if(currentTouch && !previousTouch)

```
    private void CheckCollision()
    {
        // Push current to previous and clear current
        previousTouch = currentTouch;
        currentTouch.Clear();

        for (int i = 0; i < physObj.Count; i++)
        {
            if (physObj[i].isCollisionChecked)
            {
                for (int j = i + 1; j < physObj.Count; j++)
                {
                    if (physObj[j].isCollisionChecked)
                    {
                        CollisionData data = physObj[i].collideHull.Intersects(physObj[j].collideHull);
                        if (data.touching)
                            currentTouch.Add(data);
                    }
                }
            }
        }
    }

```

Then I have my collision resolution or HandleCollision function which goes throuhg all of the collisions in list and resolves them with one iteration (I know its common to do multiple iterations to avoid jitter when multiple objects are colliding.)

```
    private void ResolveCollision(CollisionData collisionData)
    {
        // Set some easily accessed objects
        PhysObj physObj1 = collisionData.obj1 as PhysObj;
        Shape physObj1Shape = collisionData.shape1;
        PhysObj physObj2 = collisionData.obj2 as PhysObj;
        Shape physObj2Shape = collisionData.shape2;

        // Get the angle between the two objects
        Vector2 rVec = physObj1.Center - physObj2.Center;
        float theta = (float)Math.Atan2(rVec.Y, rVec.X);

        if (physObj1.isCollidable && physObj2.isCollidable)
        {
            Vector2 n = Vector2.Zero;
            // Direction of unit normal
            float dir = 0f;

            // Circle depth resolution
            if (physObj1Shape.type == ShapeType.CIRCLE && physObj2Shape.type == ShapeType.CIRCLE)
            {
                // Resolve depth penetration
                // Circles depth.X collisionData is actually the magnitude of the vector
                float mDepth = collisionData.data.depth.X;
                dir = collisionData.data.dir;
                // Direction to resolve depth
                n = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));
                physObj1.Position -= (n * mDepth) / 2f;
                physObj2.Position += (n * mDepth) / 2f;
            } // Rectangle Circle depth resolution
            else if ((physObj1Shape.type == ShapeType.RECT || physObj1Shape.type == ShapeType.ORECT) && physObj2Shape.type == ShapeType.CIRCLE)
            {
                // Resolve depth penetration
                Vector2 depth = collisionData.data.depth;

                // Get the direction of the collision
                dir = collisionData.data.dir;

                // Direction to resolve depth
                n = new Vector2((float)Math.Cos(dir), (float)Math.Sin(dir));
                physObj1.Position -= (depth * n) / 2f;
                physObj2.Position += (depth * n) / 2f;
            }

            // Apply Force Normal
            // Project the net force in the direction n
            Vector2 fN = Vector2.Dot(physObj1.fNet + physObj2.fNet, n) * n;
            physObj1.ApplyForce(fN);
            physObj2.ApplyForce(-fN);

            // Apply impulse
            if (impulse)
                physObj1.ApplyImpulse(physObj2, n);
        }
    }

```

I left quite a lot out for the sake of simplicity. But one other important thing I should note.

```
    public void ApplyImpulse(PhysObj objHit, Vector2 n)
    {
        // Calculate change in momentum ( the equation would be (1 + E) * ((v1 - v2) * n / ( 1 / m1 + 1 / m2)) )
        Vector2 p = (((Vector2.Dot((v - objHit.v), n)) / (1f / M + 1f / objHit.M)) * (1f + (E + objHit.E) / 2f)) * n;

        // Calculate final velocities
        v = v - (p / M);
        objHit.v = objHit.v + (p / objHit.M);
    }

```

E is elasticity, m is mass, v is velocity. There might be some inconsistencies in variables names or such since I changed a little bit from the original code I had.

# Answer
So the **first** thing I noticed was that when you do

```
previousTouch = currentTouch;
currentTouch.Clear();

```

this should also clear previous touch since List is a reference type.

The **second** thing is that there is no space partitioning so your collision check currently runs in O(n^2) as best case runtime.

The **third** thing is that it's weird that you calculate the atan2 of the vector between the two objects to get theta and then you only use theta to get the vector back.

```
float theta = (float)Math.Atan2(rVec.Y, rVec.X);
[...]
n = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));

```

**Fourth** there is also something to be said about the effectiveness of lists, especially in a garbage collected environment, but that varies a lot depending on implementation details.

**Fifth** You can handle your collision phase differently if you don't care if objects intersect for a few frames, by just letting them gardually push each other out by applying force.
It looks like you are trying to guarantee zero intersect, which you are currently not doing. (An object can be moved out of the first collision and then back into it when resolving the second collision)

As a **last** sidenote I think that simulating n-body attraction is just always going to be a performance nightmare, so in some way you don't really need to worry about this rest, since that's what will most definitely ruin your performance. (Although space partitioning can also aleviate that a bit since you can only check with objects that are close enough to matter)

I probably didn't notice everything but I think that's the jist of it.
> 5 votes

# Answer
I found myself that to speed up my nbody. Instead of iterating through all of i & j. With i=0, i++, j=0, j++ and setting the force of object i to fG. I can use i=0, i++, j=i+1, j++ and set the force of object i to fG and object j to -fG.
> 1 votes

---
Tags: c#, physics, monogame, optimization, collision-resolution
---


# Question
Title: Drawing circles at the background of a 3D scene and updating their size
So, here is what I am trying to do in Unity 5 (using C#). I want to draw a a 2D circle at the background of a 3D scene and apply a texture/image to fill it.

Just like it would be if the circle was in the GUI, but now being always behind everything else instead of always in front (think of a moon in the sky of a piloting game, or a distant planet in a space game, etc).

What would be the fastest way to draw such a circle and, of course, update its radius depending on the camera distance? Of course, I don't want to use a sphere, I want to learn how to that with a simple circle that gets bigger or smaller depending on the distance of the viewer.

# Answer
> 1 votes
Ok, so just of the top of my head your going to want to make a new circle(2d) and apply a texture to this then write something along these lines (and attach it to the object)

Pseudo code:

```
private gameobject player
private float scale;

update{
face the player (using transform.lookat(player))
float distance = vector3.distance(transfrom.position,player.transform.position);
transform.scale = distance / scale;
}

```

The scale in this case changes as the player gets closer or further away using the global scale variable to change the sensitivity of it. Obviously i haven't tested it but in 5 min this would be my initial solution.

If you wanted to make it more efficient, then only face the player every few updates, possibly only make it call recursively every few seconds (depending how far away the player is/ how fast the player is).

An answer is better than none... :)

# Answer
> 0 votes
You probably need a skybox or a skydome. A skybox is a box around the camera, and is always centered around it. Basically a model, wich isn't get transformed by the view matrix.

---
Tags: unity, 2d, 3d, draw-order
---


title: C++ Additive Blending Algorithm 2d Game

text:
# Question
Title: C++ Additive Blending Algorithm 2d Game
I was wondering if anyone could shed any light on whats going wrong with my additive blending here, I think I'm nearly there, currently my outcome is black squares. I have tried using both the formula's on this website here https://love2d.org/wiki/BlendMode\_Formulas to try and get my desired outcome and it doesn't seem to be working.

This is the equation I have in my notes and what I have found online. Final.Red = Bitmap.Red + Viewport.Red Similar for green and blue, RGB range is \[0-1\] or \[0-255\]

The colors I am using are 255 RGBA format.

```
void SpritePlotterForm::DrawSpriteAdd( int X, int Y, Bitmap^ SrcBitmap )
{

    int FinalViewPortRed;
    int FinalViewPortGreen;
    int FinalViewPortBlue;
    int FinalViewPortAlpha;
    for (int x = 0; x < SrcBitmap->Width; x++)
    {
        for (int y = 0; y < SrcBitmap->Height; y++)
        {
          if (SrcBitmap->GetPixel(x, y).A >= 0)
          {
                // resets to avoid corruptionj of image
                FinalViewPortRed = (SrcBitmap->GetPixel(x, y).R + GetViewportPixel(x+ X, y + Y).R)/255;
                FinalViewPortGreen = (SrcBitmap->GetPixel(x, y).G + GetViewportPixel(x + X, y + Y).G) / 255;
                FinalViewPortBlue = (SrcBitmap->GetPixel(x, y).B + GetViewportPixel(x + X, y + Y).B) / 255;
                Color ResultColour = Color::FromArgb(FinalViewPortRed, FinalViewPortGreen, FinalViewPortBlue);
                SetViewportPixel(X + x, Y + y, ResultColour);

          }
       }
    }

}

```

I think the error is to do with how I am handling my alpha values, but I have tried multiple algorithms and either, end up darkening the image, creating a whole black square, or a whole transparent square, or worst is it gets an out of bounds issue.

Image to be blended

the result I get from this algorithm (run twice, those are two seperate flames there)

Desired outcome

# Answer
> 2 votes
If you calculate the final result as final.red = bitmap.red + viewport.red and divide by 255, then you are simply averaging them out, without taking alpha into account. The way I learned to calculate transparency is a formula that is also present in the top of the page you linked:

> res.r = dst.r * (1 - src.a) + src.r * src.a
> res.g = dst.g * (1 -src.a) + src.g * src.a
> res.b = dst.b * (1 - src.a) + src.b * src.a

So that would be along the lines of

```
            // resets to avoid corruptionj of image
            FinalViewPortRed = (SrcBitmap->GetPixel(x, y).R * SrcBitmap->GetPixel(x, y).A + GetViewportPixel(x+ X, y + Y).R) * (1-SrcBitmap->GetPixel(x, y).A);
            FinalViewPortGreen = (SrcBitmap->GetPixel(x, y).G * SrcBitmap->GetPixel(x, y).A  + GetViewportPixel(x + X, y + Y).G)  * (1- SrcBitmap->GetPixel(x, y).A) ;
            FinalViewPortBlue = (SrcBitmap->GetPixel(x, y).B  * SrcBitmap->GetPixel(x, y).A + GetViewportPixel(x + X, y + Y).B)  * (1-SrcBitmap->GetPixel(x, y).A) ;

```

It is then also important to adjust the new alpha value of the resulting color! (Since 2 transparent objects over each other will result in a color that is less transparent)!

> res.a = dst.a * (1 - src.a) + src.a

Again, this woud look probably someting ike this in your code:

```
            FinalViewPortAlpha = (SrcBitmap->GetPixel(x, y).A + GetViewportPixel(x + X, y + Y).A * (1-SrcBitmap->GetPixel(x, y).A) ;

```

**EDIT:** Assuming you wanted or needed to use the formula you specified in your question, that seems to be a so called "premultiplied alpha" calculation. Your link has a brief description, but doesn't really say how alpha even comes into play.
Wikipedia has a better description. I think the most useful thing for you is the description (i manually put the **a** in, standing for alpha, the wiki has a concrete number, but we want to be more general)

> *If an alpha channel is used in an image, it is common to also multiply the color by the alpha value, to save on additional multiplications during compositing. This is usually referred to as premultiplied alpha.*

and also

> *...if this pixel uses premultiplied alpha, all of the RGB values (0, x, 0) are multiplied by **a** and then the alpha is appended to the end to yield (0, x * **a** , 0, **a** ).*

I haven't used this formula, but it seems you simply multiply alpha ( =\> \[0,1\]) to all of it's colors (so src.r * src.a, scr.g * scr.a....) and then add up the colors in the end after doing so.

PS: Checking SrcBitmap-\>GetPixel(x, y).A \>= 0 seems kind of pointless here, since alpha is \[0,1\], so that would need to always be true

---
Tags: c++, alpha-blending
---


# Question
Title: What is the advantage of binary FBX files over ASCII ones?
I know that the size does matter but except for this advantage, are their any other advantages to using binary files instead of the ASCII format in real production workflows?

ASCII files have a lot of advantages: human-readable, easier to integrate and debug, VCS, etc.

# Answer
> 5 votes
In general you don't use any such format directly as an asset in production. It's fine to add code for loading them, and to use them as an intermediate format for development, but for production you don't really go down that route. Instead, for production you want to use e.g. a model format that you can load fast and directly; e.g. and in OpenGL, you'd want to be able to do something like this:

```
void *data = glMapBuffer (GL_ARRAY_BUFFER);
fread (data, buffersize, 1, f);

```

The same would apply to any other asset type.

This approach requires no parsing whatsoever, it loads directly into the final buffer (or other container) from which it's going to be used, it's friendlier for content streaming approaches, and all the hard work of debugging/etc will (hopefully!) already have been done using the intermediate format, so those advantages don't apply.

# Answer
> 4 votes
The advantages of binary FBX over ASCII FBX are most immediately; speed of reading and the size of the file.

Another significant advantage would be that it is possible to build your own parser and asset importer for the ASCII flavour. The binary format has never been (officially) publically documented.

I would also challenge the degree of advantage ASCII FBX has over binary FBX in a few areas.

### Human Readable

While ASCII is considerably more readable than binary, it may not be practically relevant. Many exported models are large and complex to read even as ASCII text. You're unlikely to venture into the file except for debugging. This is more likely if you're building your own parser but otherwise considering how mature the format is, I don't see there is much call to poke around in it. Likewise you're only going to be fixing the reading side, since the exporter is proprietary.

### VCS

Because of the way the text is organised in an ASCII FBX, anything but the smallest changes cause merge conflicts to rival the problems you face in using the binary form.

As for production workflows my answer would only echo MFAHs response above. Ideally use FBX as an intermediate format only. Process them into a binary format well suited to your title, which may include raw buffers and the like.

# Answer
> 3 votes
Binary files load much faster than ASCII files --

```
// open it
FILE *fin = fopen( "binary.fbx", "r" ) ;
// get size in bytes
fseek( fin, 0, SEEK_END ) ;
size_t size = ftell( fin );
rewind( fin ) ;
unsigned char* bytes = (unsigned char*)malloc( size ) ;
fread( bytes, size, 1, fin ) ;
// THAT'S ALL FOLKS!

```

Meanwhile, an ascii fbx parser is pretty significant code size. Not that it'll take too long for a small model, but there is a speed advantage there.

That is about their only *advantage*. Disadvantages of binary formats are:

* Not portable (little-endian/big endian/sizeof(long) issues)
* If there is an error in the FBX exporter, extremely hard to fix
* If change version of FBX format, extreme nightmare

---
Tags: fbx
---


# Question
Title: Monogame scale/resizing texture without stretching the borders
I would like to scale or resize my texture2d but when I do it, the texture border becomes stretched.

Here's an example :

This is my original texture

And this the texture after I change the Scale:

The texture's border becomes stretched compared to the original, and I would like to preserve exactly the same border than the original texture.

Is there a way to re-scale a texture without having it stretched?

If so, could you help me find the best way to do it?

# Answer
> 2 votes
So here's the deal with 9 patches (or as @hamza-hasan called them in the comments "9 slice scaling"). Either way the concept the same.

The concept is pretty simple. Slice your source image up into 9 sections as shown in the image below. For reference I've drawn 4 red lines to represent how the texture might be sliced up to create the 9 patches. I've also numbered the patches 0 to 8.

It's worth noting that I didn't align the red lines with the exact edges where the black meets the blue. You could do this if you want, but it's not strictly necessary. In many cases the lines can be pretty rough estimates and it'll still work just fine.

Obviously, the goal is the be able to make the source image bigger (wider and taller) without stretching the borders. The 9 patch method does a pretty good job, but just keep in mind that the middle (4) and the sides (1,3,5,7) will still stretch. Depending on your texture, the effect might be great, or it could still look stretched. You sometimes have to fiddle with the numbers to get it to look okay.

When you render the box, typically the corners (0,2,6,8) won't stretch, the top/bottom (1,7) will stretch horizontally, left/right (3,5) will stretch vertically and the middle (4) will stretch in both directions.

There's a couple of ways to think about these 9 patches. One way is to think about them as rectangles, which they are, but another way is to just think about the distance between the lines and the edge of the image. That's what I've done in the following algorithm from MonoGame.Exteneded.

```
private Rectangle[] CreatePatches(Rectangle rectangle)
{
    var x = rectangle.X;
    var y = rectangle.Y;
    var w = rectangle.Width;
    var h = rectangle.Height;
    var middleWidth = w - LeftPadding - RightPadding;
    var middleHeight = h - TopPadding - BottomPadding;
    var bottomY = y + h - BottomPadding;
    var rightX = x + w - RightPadding;
    var leftX = x + LeftPadding;
    var topY = y + TopPadding;
    var patches = new[]
    {
        new Rectangle(x,      y,        LeftPadding,  TopPadding),      // top left
        new Rectangle(leftX,  y,        middleWidth,  TopPadding),      // top middle
        new Rectangle(rightX, y,        RightPadding, TopPadding),      // top right
        new Rectangle(x,      topY,     LeftPadding,  middleHeight),    // left middle
        new Rectangle(leftX,  topY,     middleWidth,  middleHeight),    // middle
        new Rectangle(rightX, topY,     RightPadding, middleHeight),    // right middle
        new Rectangle(x,      bottomY,  LeftPadding,  BottomPadding),   // bottom left
        new Rectangle(leftX,  bottomY,  middleWidth,  BottomPadding),   // bottom middle
        new Rectangle(rightX, bottomY,  RightPadding, BottomPadding)    // bottom right
    };
    return patches;
}

```

What it does is take a source rectangle and split it up into 9 rectangles representing the patches. The cool thing is you can use the same method for both the source texture and the final render.

For example, to get the source rectangles you can run it over the rectangle representing the input texture. (I'm using a `TextureRegion` here from MonoGame.Extended, standard MonoGame doesn't have texture regions but the same principle applies for `Texture2D.Bounds`)

```
_sourcePatches = CreatePatches(textureRegion.Bounds);

```

Then when you want to render the final image you can generate a new set of patches for the sprite batch. Since the same algorithm is used for the input and output rectangles, the indices of the array of rectangles should match up and the render becomes trivial.

```
public void Draw(SpriteBatch spriteBatch, Rectangle rectangle)
{
    var destinationPatches = CreatePatches(rectangle);

    for (var i = 0; i < _sourcePatches.Length; i++)
    {
        spriteBatch.Draw(TextureRegion.Texture, sourceRectangle: _sourcePatches[i],
            destinationRectangle: destinationPatches[i], color: Color);
    }
}

```

Note 1: Running the `CreatePatches` method every frame could have an impact on performance. There's potentially some optimizations to be done by caching the patches if the destination rectangle hasn't changed.

Note 2: You can also create variations of this by changing the number of patches. For example, you can remove the top and bottom sections if you only need to scale left and right. In which case there would only be 3 patches. The algorithm could be modified to remove rectangles with a height or width of zero in this case.

---
Tags: c#, textures, monogame, scale
---


title: How can I speed up this HLSL shader?

text:
# Question
Title: How can I speed up this HLSL shader?
I have written a lighting shader file that is used as the fragment shader part of a deferred lighting pipeline.

Unfortunately, each iteration seems to be adding 0.5ms to my frame time, so any more than a handful of dynamic lights results in unbearable slowdown.

So clearly I'm doing something stupid but I'm kinda new to optimising HLSL, so anything obvious you can spot would be greatly appreciated. Here is the shader code:

```
#include "DLLightingInclude.hlsli"

static const float MAX_DIFFUSE_ANGLE = 1.57079637;

Texture2D NormalGB : register(t0);
Texture2D DiffuseGB : register(t1);
Texture2D SpecularGB : register(t2);
Texture2D PositionGB : register(t3);

SamplerState NormalSampler : register(s0);

cbuffer CameraProperties : register(cb0) {
    float3 CameraPosition;
}

cbuffer LightProperties : register(cb1) {
    float3 LightPosition;
    float LightRadius;
    float3 LightColor;
};

void GetGBValues(
    in int2 screenPosition,
    in float2 texturePosition,
    out float3 normal,
    out float3 diffuseAlbedo,
    out float3 specularAlbedo,
    out float specularPower,
    out float3 position)
{

    int3 screenPos3 = int3(screenPosition, 0);
    normal = normalize(NormalGB.Sample(NormalSampler, texturePosition).xyz);
    diffuseAlbedo = DiffuseGB.Load(screenPos3).xyz;
    float4 specularValues = SpecularGB.Load(screenPos3);
    specularAlbedo = specularValues.xyz;
    specularPower = specularValues.w * 50.0f;
    position = PositionGB.Load(screenPos3).xyz;
}

FS_OUT_SPLIT main(FS_IN input) {
    FS_OUT_SPLIT result;

    float3 N;
    float3 diffuseAlbedo;
    float3 specularAlbedo;
    float specularPower;
    float3 position;

    GetGBValues((int2) input.Position, input.TexCoord, N, diffuseAlbedo, specularAlbedo, specularPower, position);

    float3 L = LightPosition - position;
    float lightDistance = length(L);
    float invAttenuation = max(0.0f, 1.0f - (lightDistance / LightRadius));
    float NdotL = max(dot(N, L), 0.0f);
    float angle = acos(NdotL / (lightDistance * length(N)));

    float3 diffuseTerm = LightColor * diffuseAlbedo * (MAX_DIFFUSE_ANGLE - angle);
    float3 V = CameraPosition - position;
    float3 H = normalize(L + V);
    float3 NdotH = dot(N, H);
    float3 specularTerm = pow(saturate(NdotH), specularPower) * LightColor * specularAlbedo * min(NdotL, 1.0f);

    result.BackBuffer = result.PreBloomBuffer = float4(diffuseTerm * invAttenuation + specularTerm * invAttenuation, 1.0f);

    return result;
}

```

And the included file, DLLightingInclude.hlsli, looks like this:

```
struct VS_IN {
    float3 Position : POSITION;
    float2 TexCoord : TEXCOORD0;
};

struct VS_OUT {
    float4 Position : SV_POSITION;
    float2 TexCoord : TEXCOORD0;
};

typedef VS_OUT FS_IN;

struct FS_OUT {
    float4 Color : SV_TARGET0;
};

struct FS_OUT_SPLIT {
    float4 BackBuffer : SV_TARGET0;
    float4 PreBloomBuffer : SV_TARGET1;
};

```

I can't really see anything particularly obvious in what I've written- but like I say, I'm kind of a noob at this.

# Answer
> 6 votes
I can't see anything fundamentally wrong with the shader, but here are a few things I find commonly done wrong with deferred shading that you might be doing.

**1**: Drawing full screen lights. The beauty of deferred shading is that you can pack your lights into geometry so that you only need to consider a part of the screen when drawing them (Like a cube with 2 times the radius as size). If instead you draw a full screen quad for every light, that will have a serious performance impact.

**2**: Render target depth. You are moving a lot of data around in deferred shading, so you have an interest in making the footprint of that as small as possible. If you can reduce the number or size of your render targets that can have a pretty big performance impact.

**3**: Rendering one light at a time rather than batching them. (Edit: You can have a static vertexbuffer and indexbuffer containing vertices for the max number of lights you want to ever render and then just patch the position and color of the lights that are active)

And lastly, you can always look at the assembly of your shader and see how many cycles it will take, so that gives you an easy way to see your own performance and compare. GPU Gems has 2 or 3 great articles on deferred shading and the performance and other issues that come with it.

---
Tags: shaders, directx, directx11, hlsl, optimization
---


# Question
Title: How can I change width of sprite Dynamically?
I want to change width of sprite dynamically but i can't perform it.!! Here i want to change only my white sprite i want to use these type of facility in my game in using AndEngine I want to display life of player

# Answer
> 5 votes
I add my code its for temporary code you can change this code set your life of player

```
    life = 10;
    final Sprite whiteSprite= new Sprite(0, 0, testRegion);
    scene.attachChild(whiteSprite);
    width = whiteSprite.getWidth();
    scale = width/life;

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            width-=scale;
            if (width > 0) {
                whiteSprite.setWidth(width);
            }
        }
    }, 5000, 1000);

```

# Answer
> 0 votes
I finally found how you can change width or height with modifiers of andengine. Don't think you need it now. But it can be helpful for others.

```
entity.registerEntityModifier(new SingleValueSpanEntityModifier(duration, fromHeight, toHeight) {
        protected void onSetInitialValue(IEntity pItem, float pValue) {}
        @Override
        protected void onSetValue(IEntity pItem, float pPercentageDone, float pValue) {
            ((CLASS)pItem).setHeight(pValue);
            //where CLASS is the class of your item (Rectangle or Sprite...)
            //as Entity class hasn't width and hight params.
            // pValue is a variable from modifier. So, you write it like that.
        }
        public IEntityModifier deepCopy() throws DeepCopyNotSupportedException {return null;}
    });

```

---
Tags: android, andengine
---


# Question
Title: How to avoid gimbal lock in Unreal Engine (c++)?
I created an orbit camera (sometimes called turntable camera; similar to the one with the "use UE3 orbit controls" setting in a static mesh view).

I attached the camera to a `USpringArmComponent` with a `TargetArmLength` set to `400`. In the `tick` function, I rotate the arm with this simple method:

```
        // Simple, clamped version
        FRotator Rotation = CameraSpringArm->GetComponentRotation();
        Rotation.Yaw += CameraInput.X * CameraRotationSpeed;
        Rotation.Pitch = FMath::Clamp(Rotation.Pitch + CameraInput.Y * CameraRotationSpeed, -85.0f, 85.0f);
        CameraSpringArm->SetRelativeRotation(Rotation);

```

I had to clamp the pitch to hide the gimbal lock problem. But this prevent users to rotate completely around objects. I don't understand why the Z rotation (the yaw) occurs on the world z axis ( `FVector::UpVector` which is `(0, 0, 1)`) and not on the local z axis. It turns out that this is exactly what I want.

I tried to solve this gimbal lock problem with this other method:

```
        // Taken from https://answers.unrealengine.com/questions/232923/how-can-i-avoid-gimbal-lock-in-code.html
        FRotator RotationDelta(CameraInput.Y * CameraRotationSpeed, CameraInput.X * CameraRotationSpeed, 0.f);
        FTransform NewTransform = CameraSpringArm->GetComponentTransform();
        NewTransform.ConcatenateRotation(RotationDelta.Quaternion());
        NewTransform.NormalizeRotation();
        CameraSpringArm->SetWorldTransform(NewTransform);

```

It works, but this time, the Z rotation (yaw) occurs on the local Z axis. How can I change it to rotate around the world Z axis, and the local Y axis, without gimbal lock?

I tried this hybrid solution, but the gimbal lock is still there:

```
        // Hybrid
        FRotator RotationDelta(CameraInput.Y * CameraRotationSpeed, 0.f, 0.f);
        FTransform Transform = CameraSpringArm->GetComponentTransform();
        FRotator Rotation = CameraSpringArm->GetComponentRotation();
        Rotation.Yaw += CameraInput.X * CameraRotationSpeed;
        Transform.SetRotation(Rotation.Quaternion());
        Transform.ConcatenateRotation(RotationDelta.Quaternion());
        Transform.NormalizeRotation();
        CameraSpringArm->SetWorldTransform(Transform);

```

I did solve this problem (a long time ago) in OpenGL using quaternions, so I tried this version:

```
        // Quaternion
        FRotator Rotator = CameraSpringArm->GetComponentRotation();
        FQuat Quaternion = Rotator.Quaternion();
        // Rotate around the world Z axis:
        Quaternion *= FQuat(FVector::UpVector, FMath::DegreesToRadians(CameraInput.X * CameraRotationSpeed));
        // Rotate around the local Y axis:
        Quaternion *= FQuat(Rotation.RotateVector(FVector::RightVector), FMath::DegreesToRadians(CameraInput.Y * CameraRotationSpeed));
        CameraSpringArm->SetRelativeTransform(Quaternion);

```

But this does not work. I also tried this:

```
        // Quaternion + transform
        FTransform Transform = CameraSpringArm->GetComponentTransform();
        Transform.ConcatenateRotation(FQuat(FVector::UpVector, FMath::DegreesToRadians(CameraInput.X * CameraRotationSpeed)));
        Transform.ConcatenateRotation(FQuat(Rotation.RotateVector(FVector::RightVector), FMath::DegreesToRadians(CameraInput.Y * CameraRotationSpeed)));
        Transform.NormalizeRotation();
        CameraSpringArm->SetWorldTransform(Transform);

```

without success.

# Answer
My hybrid solution works!

The gimbal lock was still there because I had a rotation lag on the CameraSpringArm, which does not support 6 DoF.

Removing the camera lag (`CameraSpringArm->bEnableCameraRotationLag = false;`) solved the problem.
> 1 votes

---
Tags: camera, unreal, unreal-4, orbit, gimbal-lock
---


# Question
Title: Box2D LibGDX Body.getPosition() and Body.getWorldCenter() problems
I have a problem with my game in Java with Box2D and LibGDX

I found out that when I use

body.getPosition() it is only half of that of body.getWorldCenter().

The problem here is for me that I use Joints also, which forces me into using body.getPosition().

But now my body gets drawn on the position of body.getWorldCenter().

which makes it so it looks like that

https://i.stack.imgur.com/xsTNl.png

Here is the source code where I create the Car Body

}

```
public static Body createCarBody(Vector2 position, float sizeX, float sizeY, float density, float friction, float restitution, float linearDamping, float angularDamping)
{

    System.out.println("position createCarBody " + position);
    Body body = Physics.createBody(createBodyDef(position, linearDamping, angularDamping));
    body.createFixture(createFixtureDefCar(createPolygonShape(sizeX, sizeY,position), density, friction, restitution));

    return body;
}

public static FixtureDef createFixtureDefCar(PolygonShape shape, float density, float friction, float restitution)
{
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = density;
    fixtureDef.friction = friction;
    fixtureDef.restitution = restitution;
    return fixtureDef;

}

public static PolygonShape createPolygonShape(float sizeX, float sizeY, Vector2 position)
{

    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(sizeY/2 , sizeX/2, position,0);

    System.out.println("position polygonshape " + position);

    return polygonShape;
}

```

I use the createCarBody method in my car class where it is given a Position Vector of (30,30) ( first car ) and (40,40) second car

If I print body.getWorldCenter() i get (60,60) and (80,80 )

# Answer
Instead of applying the `position` to the `Shape` if the `FixtureDef`, apply the `position` to the `Body`.

Something like this might work for you;

```
public static Body createCarBody(Vector2 position, float sizeX, float sizeY, float density, float friction, float restitution, float linearDamping, float angularDamping) {
    System.out.println("position createCarBody " + position);
    Body body = Physics.createBody(createBodyDef(position, linearDamping, angularDamping));
    body.createFixture(createFixtureDefCar(createPolygonShape(sizeX, sizeY), density, friction, restitution));
    body.setTransform(position, 0.0f); // Set the position of your body
    return body;
}

public static FixtureDef createFixtureDefCar(PolygonShape shape, float density, float friction, float restitution) {
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = density;
    fixtureDef.friction = friction;
    fixtureDef.restitution = restitution;
    return fixtureDef;
}

public static PolygonShape createPolygonShape(float sizeX, float sizeY) {
    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(sizeY/2 , sizeX/2); // Don't set a position here
    return polygonShape;
}

```
> 0 votes

# Answer
Try setting the position on the FixtureDef.

I'll assume that you already converted the units to Box2d:

```
public static Body createCarBody(Vector2 position, float sizeX, float sizeY, float density, float friction, float restitution, float linearDamping, float angularDamping){

System.out.println("position createCarBody " + position);
Body body = Physics.createBody(createBodyDef(position, linearDamping, angularDamping));
body.createFixture(createFixtureDefCar(createPolygonShape(sizeX, sizeY), density, friction, restitution, position, sizeX, sizeY));

return body;
}

public static FixtureDef createFixtureDefCar(PolygonShape shape, float density, float friction, float restitution, Vector2 position, float sizeX, float sizeY){
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = density;
fixtureDef.friction = friction;
fixtureDef.restitution = restitution;

//Set your position here
fixtureDef.position.set((position.x + sizeX / 2),
            (position.y + sizeY / 2));
return fixtureDef;
}
public static PolygonShape createPolygonShape(float sizeX, float sizeY){
PolygonShape polygonShape = new PolygonShape();
polygonShape.setAsBox(sizeX/2 , sizeY/2);
//Don't set the position on the shape

return polygonShape;
}

```
> 0 votes

---
Tags: java, libgdx, box2d, body, joints
---


title: Profiling LibGDX game with GLProfiler

text:
# Question
Title: Profiling LibGDX game with GLProfiler
I am trying to profile my LibGDX game, It runs on 60FPS on PC and 42-45 FPS on MY mobile phone. Either I improve performance and raise it to 60, or lock it at 30 (I don´t want to do this).

I have found GLProfiler on the LibGDX wiki, and I am giving it a try. (GLProfiler)

Here is how I am using it:

```
@Override
public void render(float stateTime)
{

    //my Render Code

    System.out.println(
            "  Drawcalls: " + GLProfiler.drawCalls +
                    ", Calls: " + GLProfiler.calls +
                    ", TextureBindings: " + GLProfiler.textureBindings +
                    ", ShaderSwitches:  " + GLProfiler.shaderSwitches +
                    "vertexCount: " + GLProfiler.vertexCount.value
    );
    GLProfiler.reset();
}

```

> with GLProfiler.enable() on the create() function.
>
> with GLProfiler.disable() on the dispose() function.

And this is my output:

> Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches: 60, vertexCount: 36.0
>
> Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches: 56, vertexCount: 36.0
>
> Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches: 56, vertexCount: 36.0
>
> Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches: 56, vertexCount: 36.0
>
> Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches: 56, vertexCount: 36.0
>
> Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches: 56, vertexCount: 36.0
>
> Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches: 60, vertexCount: 36.0
>
> Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches: 60, vertexCount: 36.0
>
> Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches: 60, vertexCount: 36.0
>
> Drawcalls: 35, Calls: 666, TextureBindings: 35, ShaderSwitches: 60, vertexCount: 36.0
>
> Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches: 56, vertexCount: 36.0
>
> Drawcalls: 33, Calls: 626, TextureBindings: 33, ShaderSwitches: 56, vertexCount: 36.0

This is just a couple frames, enough for the example.

I have been looking for information on how to read these numbers, I found nothing.

Do you guys know how can I learn from this information? (Identify problems maybe?)

# Answer
> 8 votes
You seem to lack some insight on your issue.

A couple of things to consider:

1. Is your *true* maximum frame rate on your PC really 60 or is it more? NVida drivers limit the frame rate to the maximum draw rate of the monitor, typically 60 Hz; this is due to the fact that there is no need to ask to draw faster than what the monitor is able to process.

By asking your driver to *not* limit to the VSync, you'll be able to see how you're doing on PC.
2. Input/output operations (`System.out.println`) typically take a lot of resource, so this might cause slowdowns and show more on your phone than on your PC, especially when testing with the print-outs.
3. Are you *sure* your bottleneck is GPU bound? Did you try to profile the rest of your application? Phones GPUs are not the only parts of a device that are less powerful than on PCs, CPUs and memory are also less powerful.

I would suggest you show us first that your issues are really related to how you use the GPU, otherwise, chances are you're probably barking the wrong tree.

As a final note, according to my current OpenGL knowledge:

* The amount of vertices you have seems to be quite low, which is OK
* I would think the ShaderSwitches correspond to how often OpenGL changes the states of what to send to the GPU. I think the common consensus is that these are the most expensive actions to do on a GPU and you would want to keep them minimal.
* I can't comment on the other items you mention.

---

*P.S.*

*Also, this is none of my business and it's really up to you, but I think it should be considered: on a phone, a higher frame rate means more battery consumption, so you should also probably test what advantages you gain by running at 60 FPS vs running at 30 or 45. (E.g. can you play twice as long with a battery fully charged at 30 FPS compared to running it at 60 FPS?)*

# Answer
> 0 votes
**I ended up giving up on GLProfiler. I will keep the question open in case someone knows the answer.**

Here is how I did basic profiling without GLProfiler:

```
long lastTime = System.nanoTime();

//mycode

System.out.println(System.nanoTime() - lastTime);

```

Not as good as using a proper Profiler, but at least I can measure times on runtime, and identify bottlenecks.

---
Tags: java, android, libgdx, profiling, profiler
---