# Question
Title: How can I merge the corners of fractally-generated borders so they look natural?
I'm using a fractal generator to generate borders around a rectangular area. It works great, but my problem is with corners.

A naive implementation when the left border overlaps the top border:

Obviously this doesn't look great. I tried averaging the weight of pixels from top and left border... not so great either.

My best shot was with iterating over a circle rather than over a line for corners, sort of like:

```
for(var i = 0; i < buffer.Length; i+= step) {
  for(var j = 0; j < buffer[(int)i]; j++) {
    PutPixel(Cos(i*CoeffStep)*CoeffRadius*j,
      Sin(i*CoeffStep)*CoeffRadius*j, ColorFor(j));
  }
}

```

Where `PutPixel` merges color into average if the pixel is already set. This however this skips some pixels at higher radii.

Example:

Setting smaller steps obviously helps, but not 100%. Anyone have any ideas what I can do?

# Answer
Another approach you can take for this is domain warping.

Rather than generating a 1D fractal along the edges, you generate a 2D fractal over the interior. For each pixel, you sample the fractal at that point to generate an offset vector, then you shade that pixel as if you were shading the nearby pixel at \[pixel position + offset\]. For pixels near the edge, this offset can change what would have been an "inside" pixel to "outside" and vice versa, changing the shape of the boundary.

Here is my rectangle before I apply any offset. Pixels inside the rectangle are coloured red, those outside are shaded in grey according to their distance from the rectangle's edge:

Applying varying amplitudes of warp, we get:

Note that the fractal peaks & valleys don't get squashed into skinny spikes at the corners, the way they do when bending a 1D fractal along a circular arc. Here the corners aren't a special case, but get the same treatment as any other point.

What's happening under the hood is that our lookup into the rectangle's domain is being warped by the offset, as visualized by this grid:

One risk with this method is, if the distortion amplitude is too high, you can get holes in the interior of the rectangle, or islands of rectangle separated from the main body. Lowering the frequency or amplitude of the fractal noise should take care of this.
> 3 votes

# Answer
You're getting aliasing in the second case since you're not rasterizing the circle correctly. Instead of iterating over r, theta, you need to iterate over pixels in the rectangle and determine from that their r, theta:

```
for(var i = 0; i < buffer.Length; i+= step) {
  for(var j = 0; j < buffer[(int)i]; j++) {
    var r = sqrt(i * i + j * j);
    var theta = atan2(j, i);
    PutPixel(i, j, ColorFor(r, theta));
  }
 }

```

And make ColorFor(r, theta)

determine the color for a particular pixel at radius r, angle theta.
> 1 votes

# Answer
I don't know how well this would work but I think you could solve your problem by selecting the maximum of the two blend edges. Wherever they overlap use whichever one has a higher value so that the edges are full opacity and the inside is a clean blend.
> -1 votes

---
Tags: fractal
---


# Question
Title: How can I make a flapper game that scales to multiple aspect ratios?
So I've never made a game before besides a basic 4:3 aspect ratio flapper, so bare with me. Recently I had this wild idea that I wanted to make this complected (for a 2d) game in cca. Unfortunately I'm stumped. At first I decided it's smart to program my game in a 16:9 aspect ratio, but then I thought about it... The iPad and Nexus 9 work in a 4:3 aspect ratio. How would one make a game (like a flapper) scale to both aspect ratios?

Edit: If it helps at all, I will be using JS... Primarily the Pixi.js library.

# Answer
> 1 votes
In the case of flapper, if centered, the 16:9 aspect ratio would give a 16.666% bonus vision ahead.

If this isn't an issue just crop it down for 4:3, penalizing those players a tiny bit.

You can also scale the obstacle sizes & movement speed to match the aspect ratios while keeping pixels square (complicated).

Otherwise "borders" for 4:3 are an option and they don't need to be black. They could be aesthetically pleasing game background. Just limit the bird range to 16:9 ratio. Put clouds that block you on top and the ground at the bottom a little higher.

---
Tags: android, ios, webgl, web, chrome
---


# Question
Title: How do you properly implement level boundaries in a physics room?
I have an issue with creating a proper boundary in GameMaker Studio when using a physics enabled room.

My room has a gravity of 0, as it is in Space. My player object has the default values, but a friction of 10 with a box shaped collision shape. I also use View0 on a 1280x720 room with a 1280x720 view. That is to be able to do screen shakes and other neat effects.

I really struggle with containing my player object properly to the room. When I use a collision with view0\_boundary and add

```
phy_position_x = phy_position_previousx;
phy_position_y = phy_position_previousy;

```

then my ship would get stuck at the screen borders very frequently.

I also tried adding some sprites that block the player off the room and created a sprite, 1280x720 and spawned them at the borders. I gave my player empty events for them and set their density to 0, making them static. However, this resulted in the same problem, I got stuck in them.

I need a smooth solution for this, obviously, to have a fun experience. I have this problem quite for a while, so please help me understanding how to do this properly.

# Answer
> 3 votes
I don't know the specifics of GameMaker, but this is how I achieved this effect in Unity.

First I defined a Boundary class that defines the limits of the play area. This class includes a method `trimToBoundary` that takes an arbitrary coordinates and clamps them to the boundary space, like this

```
Mathf.Clamp (x, xMin, xMax),
Mathf.Clamp (y, yMin, yMax),

```

Then in the player controller, I apply a force to the player ship when the player press the move button, and then fix the position by trimming it to the play area boundary.

```
transform.position = levelController.playersBoundary.trimToBoundary(transform.position.x,transform.position.y);

```

My code is inspired by this Unity3D tutorial. I hope it is useful to you.

# Answer
> 1 votes
So you're using Box2D, you should just let the engine handle collisions. (It is generally good to avoid directly setting fixture's position/rotation/speed - just apply forces. iforce2d (https://www.iforce2d.net/b2dtut/) has some awesome related tutorials.)

What you currently are doing is manually setting the position of the ship to its previous position when the ship collides with the room boundaries.

What you should do is just simply NOT do that - just set the fixture for the ship and fixture for the room boundary (optimally an edge shape), and set them to collide.

If you don't know how to make two objects collide, you can achieve this just by creating a collision event (which may be empty if you want - just put a comment in there to prevent the event to be erased automatically) in one of those objects with the other object... like this :

This will cause object 'p\_character' to collide with another object 'p\_fixture'.

# Answer
> 1 votes
I've just had this same problem, and my step-by-step fix was this:

* Make a new Object to own the collisions. Mine was called 'RoomBoundary'
* Make sure the Object's 'Uses Physics' box is NOT checked. (If you check it you'll end up with the default physics properties, which you don't want).
* In that Object, add a 'Create' Event which runs this script:

```
  // Excuse magic numbers - I have a 2048x1536 room
  var NewBoundary = physics_fixture_create();
  physics_fixture_set_chain_shape(NewBoundary, true);  // 'true' closes the loop
  physics_fixture_add_point(NewBoundary,    0,   0);
  physics_fixture_add_point(NewBoundary, 2048,   0);
  physics_fixture_add_point(NewBoundary, 2048, 1536);
  physics_fixture_add_point(NewBoundary,    0, 1536);
  physics_fixture_bind(NewBoundary, id);
  physics_fixture_delete(NewBoundary);
```
* Add a 'Collision' Event (with player in my case) which runs a script containing a comment. This tells GameMaker to enable collisions between these objects. Add identical collision Events for all objects you want this boundary to apply to.
* Add the RoomBoundary Object to the Room needing a boundary.

GameMaker will then take care of the collisions automatically using the physics system, no further action required.

(This solution was heavily based on Despicable's, and I'd have made this a comment on that answer and upvoted it, but I don't have enough rep to do either of those. Hopefully making this step-by-step adds something of value).

---
Tags: physics, game-maker
---


# Question
Title: How do I detect a line collison in LIBGDX?
I am drawing a continuous line using Pixmap. I want to check for a collision / intersection of my line with the already drawn line.

# Answer
> 1 votes
In general you can check if any Intersection exist between your two lines as below.

**Problem:** Given **n** line segments; Report all(as **k** in algorithms) Intersections.

You can implement any of these two algorithm in your desire language and use them. they take your line segments as input and return if any intersection ( Collision in your case) exists.

Note: **Time/Space complexity of these algorithms for collision detection break with k=1**. because as you see first intersection, you can stop algorithm and report collision.

---

**Solution 1:** Sweep Algorithm (Bentley, Ottmann '79)

**Time Complexity: O(n\*lg(n)+k)**

**Space Complexity: O(n+k)**

**Pseudo Code:**

```
ReportIntersections()
{

    Initialize event queue EQ = all segment endpoints;
    Sort EQ by increasing x and y;
    Initialize sweep line SL to be empty;
    Initialize output intersection list IL to be empty;

    While (EQ is nonempty) {
        Let E = the next event from EQ;
        If (E is a left endpoint) {
            Let segE = E's segment;
            Add segE to SL;
            Let segA = the segment Above segE in SL;
            Let segB = the segment Below segE in SL;
            If (I = Intersect( segE with segA) exists)
                Insert I into EQ;
            If (I = Intersect( segE with segB) exists)
                Insert I into EQ;
        }
        Else If (E is a right endpoint) {
            Let segE = E's segment;
            Let segA = the segment Above segE in SL;
            Let segB = the segment Below segE in SL;
            Delete segE from SL;
            If (I = Intersect( segA with segB) exists)
                If (I is not in EQ already)
                    Insert I into EQ;
        }
        Else {  // E is an intersection event
            Add E’s intersect point to the output list IL;
            Let segE1 above segE2 be E's intersecting segments in SL;
            Swap their positions so that segE2 is now above segE1;
            Let segA = the segment above segE2 in SL;
            Let segB = the segment below segE1 in SL;
            If (I = Intersect(segE2 with segA) exists)
                If (I is not in EQ already)
                    Insert I into EQ;
            If (I = Intersect(segE1 with segB) exists)
                If (I is not in EQ already)
                    Insert I into EQ;
        }
        remove E from EQ;
    }
    return IL;
}

```

---

**Solution 2:** Divide & Conquer Algorithm (Balaban '95)

**Complexity: O(n\*lg(n)+k)**

**Space Complexity: O(n)**

---
Tags: collision-detection, libgdx
---


title: 2D collision of thrown objects in Unity

text:
# Question
Title: 2D collision of thrown objects in Unity
I am currently working on a game inspired by traditional 2D Zelda games ("Link To The Past", etc.) in Unity using the 2D settings.

I am looking for the best way to handle objects that the character throws and how to handle the collisions correctly given the perspective of the camera. A thrown object is rendered further up the screen to create the illusion it is in the air however due to this it will collide with enemies and objects that are not on it's current plane.

Below is a screenshot of "Link To A Past" for those who aren't familiar with the perspective of the game.

I have thought about two ways to potentially implement this system but both don't feel like good the solutions.

1. Turn off collision during the throw until near the end of the throw. I feel for this solution that different colliders would be required to ensure the correct object is experiences the collision. The issue I see with this solution is that it doesn't account for taller objects. If I throw an object directly at a wall the object should detect that.
2. A system where using Unity's physics layers I turn layers off during the flight and based off the location of the thrown object. For example turning off the physics layers of objects that are above the object but shouldn't be hit due to the perspective. This method seems like a lot of work but could be a solution to the problem.

Any thoughts for better solutions or refinements would be much appreciated.

# Answer
You might be able to use a combination of the two approaches. You could turn off the collider of the thrown object when it's lifted, and use a simple, invisible, collider placed on the body like so:

You could then fire this collider directly out from the body. It should be on the same plane as the player and the enemies, so it seems like handling hits from there should be simple. In ALttP (as far as I can remember), you can't swing under/over enemies that are on the same plane. So, anything that this invisible collider hits would also register a hit by the pot.

Another approach might be to just set a picked up object's Collider as a Trigger. Then, during OnTriggerEnter, you could check whether or not this was something to ignore (the north wall), or an enemy (or other "hittable" entity).

In either case, then just kick off damage/animations after the appropriate collision.
> 1 votes

---
Tags: unity, 2d, collision-detection
---


# Question
Title: When should I set a texture as a shader resource in order to read it?
I'm writing a Direct3D 11 HLSL shader with SharpDX. What I want to do is write the depth to a texture in one pass and read it in the next one. After declaring the texture, do I have to set the depth texture and the shader resource view per frame, or just once when attaching?

```
this.depthStencilShaderResourceVariable = this.effect.GetVariableByName("DepthTexture").AsShaderResource();
this.depthStencilShaderResourceVariable.SetResource(this.depthTextureShaderResourceView);

```

# Answer
D3D11 will prevent you from binding a shader view of a resource *and* a render view of a resource simultaneously.

Consequently you will need to bind and unbind the views every time you want to read or write to the depth texture; you can't just bind them and leave them that way for the lifetime of your program, because you can't have both views bound simultaneously.
> 1 votes

---
Tags: c#, textures, shaders, directx11, sharpdx
---


# Question
Title: How does XNA's KeyboardState represent all keyboards?
I already understand how to work with `Keyboard` and `KeyboardState`, but when debugging I happened to take a look at the `KeyboardState`'s non-public members via the VS debugger. I expected to see a large list of values, but instead, only saw 8 **uint**s at a static level, and another 8 **uint**s per instance:

```
Non-Public members  (static)
    stateMask0  uint    976757505
    stateMask1  uint    67108863
    stateMask2  uint    3221225470
    stateMask3  uint    4294967295
    stateMask4  uint    196863
    stateMask5  uint    4244635647
    stateMask6  uint    4160752641
    stateMask7  uint    1876688932

Non-Public members  (instance)
    currentState0   uint    0
    currentState1   uint    0
    currentState2   uint    0
    currentState3   uint    1048576
    currentState4   uint    0
    currentState5   uint    0
    currentState6   uint    0
    currentState7   uint    0

```

There are 32 bits per **uint**, so having 8 of them essentially acts as a field of 256 boolean values, which loosely corresponds with the `Keys` enum type, so I *assume* that the static values act as a way to test which buttons are present on a device. However, XNA supports up to 4 keyboards, so I'm not sure how it both translates this to a button state, nor how it can differentiate between different keyboards in this way.

# Answer
XNA only supports one *keyboard*. It supports up to four *chatpads*, which look exactly like keyboards in terms of the state they track (note the subtle differences in the overloads of `Keyboard.GetState`).

Anyhow, `KeyboardState` object *just* reflects the state of a keyboard or chatpad. On its own, it doesn't know or care about whether or not it's representing the state of the keyboard or the state of a particular player's chatpad, or what.

When you call the `GetState` overload that takes a player index, the `Keyboard` interface can kill out the `KeyboardState` with the appropriate bits for the specified player at that point, so `KeyboardState` itself only needs enough storage to represent a single keyboard state.
> 4 votes

---
Tags: xna, keyboard
---


# Question
Title: Can you do a stencil glow with native GM:S commands?
I am looking to a stencil glow on GM:S with d3d\_\* functions.

I could not find anything how to access the stencil buffer though.

Is it even possible to access the stencil buffer without using an external .dll?

# Answer
No, it isn't possible to access the stencil buffer using the native GameMaker API to D3D. The API documentation reveals that GameMaker exposes only a limited subset of the D3D API, more-or-less wrapped up in an easy-to-consume "immediate-mode" style.

There is no facility for accessing a stencil buffer in that API.
> 1 votes

---
Tags: game-maker, stencil
---


title: Boost per-pixel rendering

text:
# Question
Title: Boost per-pixel rendering
I'm writing my own renderer in pure java without any external libraries. I'm using per-pixel rendering. I'm rendering an image with this method:

```
public void renderImage(int x, int y, RawImage image) {
        int[] img = image.getPixels();

        if (x >= surface.getWidth() || y > surface.getHeight())
            return;

        for (int i = 0; i < image.getWidth(); i++) {
            int xp = x + i;
            if (xp < 0)
                continue;
            if (xp >= surface.getWidth())
                return;
            for (int j = 0; j < image.getHeight(); j++) {
                int yp = y + j;
                if (yp < 0)
                    continue;
                if (yp >= surface.getHeight())
                    break;
                int pos = xp + yp * surface.getWidth();
                if (pos < 0 || pos >= pixels.length)
                    continue;
                pixels[pos] = blendMode.getColor(img[i + j * image.getWidth()], pixels[pos]);
            }
        }
    }

```

But if I render 500 images (with the size of 128x128) my FPS drops down to around 7. Is there anyway to make this more efficient?

The blendMode.getColor() is the blending I implemented. In this example I'm using additive:

```
public int getColor(int c1, int c2) {
        float a = (float) ((c1 & 0xff000000) >>> 24) / 255f;
        int red = (int) ((c1 & 0x00ff0000) * a + (c2 & 0x00ff0000)) + BlendMode.tint;
        int grn = (int) ((c1 & 0x0000ff00) * a + (c2 & 0x0000ff00)) + BlendMode.tint;
        int blu = (int) ((c1 & 0x000000ff) * a + (c2 & 0x000000ff)) + BlendMode.tint;
        return 0xff000000 + (red > 0x00ff0000 ? 0x00ff0000 : red) + (grn > 0x0000ff00 ? 0x0000ff00 : grn) + (blu > 0x000000ff ? 0x000000ff : blu);
    }

```

Thanks for any help!

# Answer
When you really want to get good performance, implement it in hardware using pixel shaders. The graphic cards GPU is optimized for performing the same operation on lots and lots of values in parallel, so it does so really quick. When you don't want to learn GPU programming, there are many libraries available which implement many common blend effects in hardware and offer them to you with an easy to use API.

However, when you are determined to create your own CPU-only solution, you can try to speed it up by using parallelization. Almost all desktop PCs (and even some mobile phones) nowadays have multi-core processors. Each core can independently execute an own thread with the full speed of the CPU. When you create multiple threads (one for each CPU core) and divide the work in a way that each CPU has its own workload and doesn't need to communicate with the others until their work is done, you will reach a much higher data throughput.

Multithreading in Java is implemented best with a `ThreadPoolExecutor`. To create one which uses all available processors, use the handy static constructor method `Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors() );`.

You assign new tasks to execute in parallel by passing `Runnable` objects to the `execute( Runnable )` method of your ThreadPoolExecutor. Multithreading works best when threads are able to work on a single task for a long time, so the tasks should be as large as possible.

However, be aware of a pitfall: You have no way to predict in which order the Runnables will be finished. This will cause problems when you want to draw images in a specific order. This is not an issue when you only use additive blending where draw order is irrelevant, but it can be a problem with many other blend modes.
> 2 votes

# Answer
I don't know what `RawImage` exactly is here, but once you access pixel data of a Volatile or BufferedImage in Java you lose hardware acceleration. So even if these images were stored in vram before you called `renderImage`, they will no longer be once you access the underlying pixel array.
> 2 votes

---
Tags: java, rendering, per-pixel
---


# Question
Title: How can I get a reference to a object in the world in UE4?
I'm coding a simple maze game in UE4 and I have everything I wanted to implement done except having an obstacle in the scene. What I have is a simple `Obstacle` class which is a child of an `Actor` class.

Now in the scene I have a `Blueprint` which is a child of the `Obstacle` class and this `Blueprint` is placed in the maze. What I'm trying to achieve is when the player collects so many objects (let's say 10) then the `Obstacle` will be destroyed but I don't know how to get a reference to that `Obstacle` object in my code.

```
AObstacle* Obstacle /////// This is where I don't know how to initialize the object
if (MyCharacter->collectedPickUps >= requiredAmountOfPickups)
{
    Obstacle->Destroy();
    Obstacle->isActive = false;
}

```

# Answer
I have managed to sort it out. Basically I have to use an Actor Iterator which iterates through every Obstacle object in the game world. Here is the code:

```
for (TActorIterator<AObstacle> ObstacleItr(GetWorld()); ObstacleItr; ++ObstacleItr)
{
    if (MyCharacter->collectedPickUps >= requiredAmountOfPickups)
    {
        ObstacleItr->Destroy();
        ObstacleItr->bIsActive = false;
    }
}

```
> 6 votes

---
Tags: c++, unreal, unreal-4
---


# Question
Title: How do I add my phaser.js game to my pre-made web page?
First off, it's my first time doing a little bit of game development, and I have no idea of the normal flow of making a game, let alone a browser game.

My game uses the phaser framework of HTML and JavaScript. It is a simple game based on the 2D space impact game. I was able to run the game on an empty HTML site with only head, title, and body tags.

This is the code to plug in my game to the blank HTML site:

```
<script type="text/javascript" src="game.js" type="text/javascript"></script>

```

But when I tried to add it to my pre-made website, it won't show. Am I missing anything? Do I need to put it in an iFrame, although I know phaser builds on a canvas.

# Answer
> 3 votes
Thanks for the help. I solved my own problem. it seems that a simpler way to put it would have to place the game on another html page and then embed it with an `iFrame` tag! like

```
<iframe src="game.html" height="550" width="800">game not available</iframe>

```

And the text "game not available" is a displayed text when the iFrame fails no embed the content from the source as a DEFAULT.

The reason for this problem might have been the conflicting javascript libraries of the Twitter bootstrap im using and the js library of the phaser framework.

---
Tags: javascript, html5, phaser
---


# Question
Title: SDL2 Gamepad triggers trigger when disconnecting the pad
I'm using MonoGame and SDL2. I'm having a strange problem with the Gamepad. When I disconnect it during the game, before the disconnected event fires, the left and right triggers return values as if they were half-pressed.

The following code demonstrates the problem. Left or right trigger isn't really being pressed at all.

(From this source file https://github.com/dineshkummarc/MonoGame-2.5.1.0-0/blob/master/MonoGame.Framework/Desktop/Input/GamePad.cs)

```
GamePadTriggers triggers = new GamePadTriggers(c.LeftTrigger.ReadFloat(device), c.RightTrigger.ReadFloat(device));
// The following is debug code added by me
if (c.LeftTrigger.ReadFloat(device) > 0) {
    var rawSDLvalue= SDL.SDL_GameControllerGetAxis(device, (SDL.SDL_GameControllerAxis)(c.LeftTrigger.ID));
    Console.WriteLine("DURRURRRURRRRRRRR WHY IS IT NOT ZERO, IT SHOULD BE????" + c.LeftTrigger.ReadFloat(device) +" RAW "+rawSDLvalue);
}

```

Is there any real solution to this? Since the disconnected event fires afterward, I have no means to distinguish whether the triggers were really pressed or not. Any ideas? Are other SDL2 users experiencing this too?

# Answer
> 0 votes
I would guess this is due to the way triggers are implemented by your hardware. Often they are a single axis, with unpressed at -, fully pressed at +, and 0 when they are halfway pressed. This certainly happens with my classic Xbox controllers, and can cause issues when software thinks you are holding the axis fully negative when in fact you are not touching it. So what happens is a higher level software like SDL remaps driver output to something sensible.

I think what is happening is that when you unplug, Windows still allows you to read for a brief period, and just returns 0 for all axis/controls. This is then remapped to "halfway pressed" by the same remapping code. This seems like a bug, but there might not be anything SDL can do about it if Windows is sending spurious events like this.

---
Tags: sdl, gamepad
---


# Question
Title: Collision detection between triangle and polygon
I have some difficulties to understand how to be sure if there is a collision between a space ship (black) and an asteroid (in blue). A space ship is placed on a case and an asteroid comes from the right, like on the image.

Also Y1 != Y2, there are not exactly on the same line. What is the best way, in that case, to detect if there is a collision ? Is AABB collision the correct algorith I need ?

# Answer
I think either AABB collision test or circle-circle is sufficient for your needs. Usually it is not necessary to have perfect pixel level precision in determining whether 2 objects hit.

For circle-circle, have all your objects have a center x,y and a radius r; to determine whether 2 circles overlap: test (obj1.x-obj2.x)^2 + (obj1.y-obj2.y)^2 \> (obj1.r + obj2.r)^2

For box, have all your objects have x,y, width and height, and check whether the box overlap in x axis and y axis.

Edit: In case that you really really want to use triangle - polygon level of precision, you need to first implement/find a intersection test for lineSegment vs lineSegment. Then for the intersection test between 2 polygons, test whether any combination of their edges intersects OR whether one object fully contains the other (point in shape test).
> 1 votes

# Answer
To complete @user55564 I give some more information about `line segments intersection`.

In general you can check if any Intersection exist between your two polygon (even non-convex) as what I've described Here.
> 0 votes

---
Tags: c++, collision-detection
---


title: Space invaders implementation

text:
# Question
Title: Space invaders implementation
I'm just wondering about the implementing of the collision response of bullets and the fours obstacles. https://www.youtube.com/watch?v=LCNTwG3MGEg

When a bullet hit, a one black pixel is overwritten. How would one implement it in modern games, because what I feel that they overwrite the framebuffer, but right now I will only swap the sprites or images of different hit-obstacles.

If we say we will draw it as a pixels of bitmap, should then I make then a pixel to pixel collision detection If I want to clone the same behavior?

# Answer
I'd probably use a 1 bit texture (more if you want to store more states) and then draw it using a shader (or a second texture you only modify once some pixel is hit).

So yes, this would essentially mean you're working with a pixel perfect collision detection, but you wouldn't necessarily use a full bitmap/texture (1 bit per pixel vs. 32 bits per pixel).

Of course, for performance reasons you'd first check whether your shot is actually inside the bounding box of the obtsacle and then determine whether it actually collides.

As for drawing, there are many alternative possibilities, e.g. you could use voxels, a second texture with more details, or even some kind of 3D mesh (think of the different *Worms* games and how they're drawing their map).
> 1 votes

---
Tags: c++, marmalade
---


title: Trajectory of a spinning ball

text:
# Question
Title: Trajectory of a spinning ball
How do I would precalculate trajectory of a kicked ball, when it's spinning?

I'm applying spinning using simplified Magnus effect every frame like this and it works:

```
acceleration += swerve × velocity

```

My question is: do the equation below for calculating object trajectory can be extended to include the ball spinning?

```
position = start + 0.5*acceleration*time^2 + velocity*time;

```

I'm using Euler integration and ball moves fine. I just want to know how to predicts ball's movement path.

# Answer
> 1 votes
There is such an equation, but it's not easy to obtain. Because the magnus effect depends on the ball's current velocity, it changes when external forces are applied. You cannot calculate the position of the ball by linearly summing the contributions of different forces. If you were hoping you could simply add a few terms to \\$x(t)=\frac{1}{2}at^2+vt\\$, you're out of luck.

Numerical integration is a valid way of predicting the balls trajectory and doesn't require you to actually move the ball if you use a different set of variables. If you want to use a direct approach, you might want to use a tool that can solve a system of differential equations. I used Mathematica to obtain the following equations for a ball starting off with a set velocity and being subject to a gravitational acceleration *-g* in the z-direction and a magnus force \\$F\_{mag}=c\omega\times v\\$, for brevity condensed into: \\$a\_{mag}=r\times v\\$.

```
system = {
    vx'[t]==ry vz[t]-rz vy[t],
    vy'[t]==rz vx[t]-rx vz[t],
    vz'[t]==rx vy[t]-ry vx[t]-g,
    vx[0]==vx0,vy[0]==vy0,vz[0]==vz0
};
DSolve[system,{vx,vy,vz},t]
Integrate[%,t]

```

With a few tweaks, assumptions and some rewriting here and there, the result still looks dreadful, but is computationally not all that expensive.

Direct equations according to Mathematica:

$$\begin{align} x(t) =&\frac{1}{r^3}(-\frac{1}{2}t(grtr\_xr\_z+2grr\_y-2rr\_xr\_yv\_y(0)-2rr\_xr\_zv\_z(0)-2rr^2\_xv\_x(0))+\\ &sin(rt)(gr\_y+r^2\_yv\_x(0)-r\_xr\_yv\_y(0)+r^2\_zv\_x(0)-r\_xr\_zv\_z(0))-\\ &\small{\frac{cos(rt)(gr\_xr\_z+r^2\_xr\_yv\_z(0)-r^2\_xr\_zv\_y(0)+r^3\_yv\_z(0)-r^2\_yr\_zv\_y(0)+r\_yr^2\_zv\_z(0)-r^3\_zv\_y(0))}{r})}\\ y(t)=&\frac{1}{r^3}(-\frac{1}{2}t(grtr\_yr\_z-2grr\_x-2rr\_xr\_yv\_x(0)-2rr\_yr\_zv\_z(0)-2rr^2\_yv\_y(0))-\\ &sin(rt)(gr\_x+r^2\_x(-v\_y(0))+r\_xr\_yv\_x(0)-r^2\_zv\_y(0)+r\_yr\_zv\_z(0))-\\ &\small{\frac{cos(rt)(gr\_yr\_z-r\_xr^2\_yv\_z(0)+r^2\_yr\_zv\_x(0)+r^3\_x(-v\_z(0))+r^2\_xr\_zv\_x(0)-r\_xr^2\_zv\_z(0)+r^3\_zv\_x(0))}{r})}\\ z(t)=&\frac{1}{r^3}(-\frac{1}{2}tr\_z(grtr\_z-2rr\_xv\_x(0)-2rr\_yv\_y(0)-2rr\_zv\_z(0))+\\ &\small{\frac{cos(rt)(gr^2\_x+gr^2\_y-r\_xr^2\_zv\_y(0)+r\_yr^2\_zv\_x(0)+ r^3\_x(-v\_y(0))+r^2\_xr\_yv\_x(0)-r\_xr^2\_yv\_y(0)+r^3\_yv\_x(0))}{r}}-\\ &sin(rt)(r^2\_x(-v\_z(0))+r\_xr\_zv\_x(0)+r\_yr\_zv\_y(0)-r^2\_yv\_z(0)))\end{align}$$

If you didn't think these equations were getting out of hand already, you most likely will if you were to add more forces to the model. Unless you feel the need for the accuracy and speed these equations can provide, I recommend sticking with code that fellow mortals can read and maintain.

# Answer
> 0 votes
First create a vector. It's angle is equal to ball spin speed (degrees per frame) plus the balls trajectory angle ( looking down from the sky). Set the magnitude to however much you want it to effect the trajectory of the ball. Add this vector to the balls vector, or position if you don't use vectors. Probably a good idea to make the magnitude diminish over time, that way it won't turn forever. This can be applied in 2d games, and can be modified to be used in the third dimension by doing the same process from the side.

---
Tags: mathematics, physics, projectile-physics, trajectory
---


# Question
Title: Game prelauncher with configurations (resolution/quality)
I've seen that a lot of games have the exactly same configuration screen before the game launches, as you can see in the following screenshot.

Is this screen generated by some tool, for example, Unity, GameMaker or anything, or is it a plugin that we can use?

# Answer
The launcher in question is included by default for games built with Unity and is called the resolution dialog.

Currently there is very little customization that can be done to this dialog though preset values can be defined using the Player Settings.

Additionally the dialog can be disabled altogether within the player settings using the ResolutionDialogSetting enum.

> Disabled: Never show the resolutions dialog.
>
> Enabled: Show the resolutions dialog on first launch.
>
> HiddenByDefault: Hide the resolutions dialog on first launch.
> 13 votes

# Answer
This really depends on the actual toolset that's been used in creating some game. There's no such standard screen built into Windows or anything like that. If you see the same window in two different games, then either both use similar/same ressources or one has been modelled after the other.

Are there such plugins or libraries available? Most likely, but listing them here would most likely be considered off-topic/out of scope (since there's no definitive answer to that).

However, in general, I'd try to avoid such setup screens. They're only quite popular in games that have been ported from consoles to PCs or games where the creator isn't supposed having to fiddle around with them (systems like RPG Maker or GameStudio etc.).

They might make writing the program easier (since you no longer have to worry about changeable settings while the game is running), but at the same time it limits the user's ability to adjust settings on the fly, which might also be considered negative.
> 1 votes

---
Tags: resolution, configuration
---


title: Deploying MonoGame on Android

text:
# Question
Title: Deploying MonoGame on Android
I've developed a game using MonoGame for Android (with Xamarin). When deploying to my Android device (via the Xamarin Studio IDE) it installs 3 apps - Monogame-Android-8-support, Monogame-Shared-Runtime and the actual game.

Now I'd like to know how you can package all those into one APK in order to publish the app.

# Answer
> 2 votes
Expanding on @craftworkgames comment, there's a xamarin guide on publishing. Essentially, the steps are:

1. Compile for release (Disable debugging and build in release mode)
2. Create a private key (This is so you can sign the APK)
3. Zipalign the APK (This is for optimizations with Android)

After this, you have to jump through various google hoops to get it on the play store, starting with creating a developer account, submitting assets like an icon, screenshots, a promo graphic (optional) and then uploading to google play if it's accepted.

The link to the guide should go into further detail if you need more guidance.

---
Tags: c#, android, monogame
---


# Question
Title: Unity 3d 4.6b New GUI system doesn't take touch when already a touch event is occurring in 3d scene
I know this is beta version but..

I have a Canvas-\>Button which works fine when I tap it normally.

I have a joystick in my scene which is drawn by separate camera other than mainCamera.

now, while i am operating joystick without leaving it, if I tap on he Canvas-\>Button - it does not respond. When I lift finger from joystick and tap on it, it works fine. Same goes for another Canvas-\>Toggle control.

It has something to do with the layering or anything else...I'm not sure?

# Answer
> 1 votes
## Using the current version of Unity 4.6 I experienced and resolved a similar issue:

My GUI interaction had become non-responsive and unpredictable whilst performing other actions (Particularly while moving the player with keyboard input `WASD`). My resolution was disabling "Send Navigation Events" from the Event System that was managing my canvas interactions.

Please find the docs here:

http://docs.unity3d.com/460/Documentation/ScriptReference/EventSystems.EventSystem-sendNavigationEvents.html

Coming from web, to me this felt like a weird "focus" issue. and setting that "Send Navigation Events" to false resolved everything.

---
Tags: unity, unityscript
---


# Question
Title: How can I load raw Bayer images using OpenGL?
I want to load a raw Bayer format image and convert it to RGB using OpenGL.

So far I have played around with `glTexImage2D()` and loaded a Bayer image as a monochrome texture. My question is: how can I do per-pixel operations on this texture so that I can convert it to an RGB image?

# Answer
> 2 votes
This isn't a trivial task for someone new to graphics programming, I'm assuming you know how to write fragment shaders and sample textures.

To convert the Bayer image to an RGB texture you'll want to point sample the monochrome Bayer image, and do the interpolation in the fragment shader.

For each destination pixel, you'll know the value of one channel - the one for the colour of the filter over that pixel. For the other two channels you'll need to sample some of the surrounding pixels and interpolate. This gets more complicated for edge pixels, and for that reason the easy option is to throw away a pixel or two along each edge of the result.

Let's say the filter looks like this, where R, G and B represent the colour of the filter over the pixel:

```
RGRGRGRG
GBGBGBGB
RGRGRGRG
GBGBGBGB

```

For each R pixel, one way to calculate the G value is to take the average of the four pixels each side of it, as they all have a green filter. To calculate the B value you can do the same thing diagonally.

In pseudocode a basic conversion to RGB would look something like this:

```
if (x % 2 == 0 && y % 2 == 0)
{
  // Red pixel in filter
  result.r = bayer[x,y];
  result.g = (bayer[x+1,y] + bayer[x-1,y] + bayer[x,y+1] + bayer[x,y-1]) * 0.25;
  result.b = (bayer[x+1,y+1] + bayer[x+1,y-1] + bayer[x-1,y+1] + bayer[x-1,y-1]) * 0.25;
}
else
// TODO: Handle the other cases

```

---
Tags: opengl
---


# Question
Title: Is white the best base color to start with when planning to shade sprites within Unity?
I'm looking into prototyping a game in Unity which will consist of solid square sprites / tiles. I figure I can represent different types of objects with different colors for each of the tiles in the game.

**I figure that I can import a single square sprite and shade it appropriately in Unity as opposed to imported squares of many different colors.**

My experience with adjusting the hue and saturation within Photoshop shows that white is not an easy color to change as things that are white often stay white. My testing in Unity shows that I can change the "color" of a sprite to anything other than white and the sprite is seemingly shaded appropriately, despite what I would have thought given my Photoshop experience.

Since white objects do seem to take on the appropriate color shading when changed within Unity my gut tells me that this is the best base color to begin with, meaning that I can import a single white square sprite and simply adjust the color to represent different objects and object states.

Is a white sprite actually the best color sprite to begin with and why does something like this work in Unity as opposed to adjusting the hue and saturation within Photoshop?

# Answer
**White is the best** base color for true representation. Also keeping your sprite grayscale can make for some easy color adjustments for teams, etc.

Unity applies a **`Multiply` blend mode** to the sprite texture and color.

Unity's Color type is ranged from 0 to 1 inclusive.

Color.White is equal to `(1, 1, 1, 1)`.

Knowing that `1` times anything is itself.

If the grayscale `texture` is blended with the Sprite Renderer `Color` field, each pixel is itself. Changing this field will simply multiply each uniform grayscale value by each component of the color.

---

You can play with the Multiply blend mode in your favorite image editor like Photoshop or GIMP.
> 13 votes

# Answer
# Sprites-Additive.shader \- GitHub Gist

Unity colors have 4 float values typical of many color formats RGBA, corresponding to the individual percentage color values Red, Green, Blue and the Alpha transparency channel.

Also as mentioned above the default "Tint" applied by Unity is a multiplicative shader Photoshop calls this effect "Multiply" and the process is literally multiplying the color values in the pixels of your sprite with the color value selected.

The problem with this is, a Multiplicative color math shader will ALWAYS produce the same hue (if you "multiply" by white) or darker color if you multiply by anything else. I came across the situation where I wanted the exact opposite effect in a blacksmithing type situation. Heated metal should not be Multiplied by Yellow to produce a darker hue:

Instead, I rewrote Unity's default multiplicative shader to be an additive one. The results were more along the lines of what I was looking for:

I'll provide a gist to the rewritten Sprites-Additive.shader if anyone is interested.

Here is a good reference on color terminology and modes: http://www.northlite.net/ps/blend.htm
> 3 votes

---
Tags: unity, sprites, color
---


# Question
Title: Box2d C++ x velocity slowing for no apparent reason
I'm making a 2d platformer in C++, using Box2d for physics and sfml for rendering, I want the player character to move with a constant velocity in the x direction, and to jump when the spacebar is pressed, maintaining it's x velocity. At the moment however, jumping slows the x velocity to a crawl, and falling large distances does the same

```
b2Vec2 jumpForce(120.0f , -500.0f);
playerBody->ApplyLinearImpulse( jumpForce, playerBody->GetWorldCenter(), true);

```

is how the impulse is applied when I want to jump, and

```
b2Vec2 moveSpeed(120,0);
playerBody->SetLinearVelocity(moveSpeed);

```

is the velocity the body is initialized with, I've turned both linear damping and friction to 0, but with no success.

If anyone has any idea how to solve this issue your help would be greatly appreciated.

edit: These are a couple of solutions I've tried

```
b2Vec2 jumpForce(playerBody->getLinearVelocity().x, -500.0f);
playerBody->ApplyLinearImpulse( jumpForce, playerBody->GetWorldCenter(), true);

b2Vec2 jumpForce(playerBody->getLinearVelocity().x, -500.0f);
playerBody->SetLinearVelocity( jumpForce, playerBody->GetWorldCenter(), true);

```

# Answer
Your problem is that you're exceeding Box2D's maximum offset-per-physics-update. This is a common mistake.

> There is a maximum movement limit of 2.0 units per time step give in the file b2Settings.h in the source code.

Assuming that you're running at 60 updates per second, your starting velocity of 120 units per second is already exactly at Box2D's maximum movement speed, and adding any more velocity in any direction will result in clamping.

The best solution for this is to change the way that you represent space in Box2D; instead of whatever units you're using at the moment (I assume you're using 'pixels', as that's the most common way people wind up with really high velocities in simulations), use 'meters', or something else which will allow your velocity values to be lower, so you won't reach the maximum movement-per-physics-update limit so quickly.
> 2 votes

---
Tags: c++, box2d, platformer
---


# Question
Title: Libgdx--how to store every single point drawn using touchdragged?
Basically i am trying to detect line collision. The problem is when intersection occurs quickly(touch dragged is done quickly like fling), the collision is not detected. It seems as if 'touch dragged' doesn't store all points.

# Answer
Touch screen record discrete points with a non-constant rate depending on how busy the CPU is and how reliable the hardware readings are.

You need to "connect" those points as lines (old point from last game loop to new point) when checking for collisions and calculate line-line or line-circle intersection (or other type of line-object intersection).

You can also sub-divide the line and test multiple points on the line for collision to keep things simple.
> 2 votes

---
Tags: collision-detection, libgdx, touch
---


# Question
Title: physically based shading, how to combine specular & diffuse parts?
After writing 'standard' phong & blinn shaders for a while, I recently started to dabble in physically based shading. A resource that helped me a lot are these course notes, especially this paper \- it explains how to make blinn more shading physically plausible.

I implemted the blinn model propsed in the paper, and I really like how it looks. The most significant change proposed ( imo ) is the inclusion of the fresnel reflectance, and this is also the part that gives me problems. Unfortunately, the author chose to focus on the specular part only, omitting diffuse reflectance. Given e.g. a lambertian diffuse reflection, I just don't know how to combine it with the 'improved' blinn - because just adding diffuse & specular parts does not seem to be right any more.

In some shaders I've seen a floating point 'fresnel term' in range 0 - 1 being used, based on the indices of refraction of the participating media. Schlick's approximation is used every time:

```
float schlick( in vec3 v0, in vec3 v1, in float n1, in float n2 )
{
    float f0 = ( n1 - n2 ) / ( n1 + n2 );
    f0 *= f0;
    return f0 + ( 1 - f0 ) * pow( dot( v0, v1 ), 5 );
}

```

Doing it like this, one can then linearly interpolate between diffuse and specular contribution based on the fresnel term, e.g.

```
float fresnel = schlick( L, H, 1.0002926 /*air*/, 1.5191 /*other material*/ );
vec3 color = mix( diffuseContrib, specularContrib, fresnel );

```

In the paper, the author states that this approach is incorrect \- because it basically just darkens the specular color whenever L is parallel or nearly parallel to H - and that instead of computing a f0 based on the indices of refraction, you should treat the specular color itself as f0 and have your schlick approximation compute a vec3, like this:

```
vec3 schlick( in vec3 v0, in vec3 v1, in vec3 spec )
{
    return spec + ( vec3( 1.0 ) - spec ) * pow( dot( v0, v1 ), 5 );
}

```

This results in the specular color going towards white at glancing angles.

Now my question is, how would I introduce a diffuse component into this? At 90° the specular contribution is fully white, this means all incoming light is reflected, so there can't be a diffuse contribution. For incidence angles \< 90°, can I just multiply the whole diffuse part with ( vec3( 1 ) - schlick ), i.e. the proportion of light that isn't reflected?

```
vec3 diffuseContrib = max( dot( N, L ), 0.0 ) * kDiffuse * ( vec3( 1.0 ) - schlick( L, H, kSpec ) );

```

Or do I need a completely different approach?

# Answer
The short answer:

Does it looks good enough?

* Yes - Keep it.
* No - Fiddle with it some more.

Long answer:

Getting accurate realistic physical based shading requires more GPU power than is possible, you'll always have to resort to faking things for the simple reason that a computer cannot simulate the entire universe, not even the entire visible light spectrum.

It is the "uncanny valley" of shading.

Not just due to ambient lighting and occlusion but for example external environments both day and moonlight have a huge amount of UV spectrum light a tiny bit of which which gets shifted back to visible spectrum by various materials, mostly organic ones. Different types of fluorescent tube lighting and HID also emits a good amount of UV light.

The effect is subtle but thanks to years of evolution the brain instinctively process it as this meant the difference between a good meal and possibly a long excruciating death so if something is ever-so-slightly off our brains sound the "something is wrong" alarm.

Cartoony, unrealistic, and almost-realistic-but-intentionally-off-by-a-good-margin (eg: Halo) art styles avoid this issue.

Another issue is that no two humans have the same RYGBL receptor presence nor response curve while monitors are strictly RGB and therefore cannot perfectly reproduce images for all humans. (Red, Yellow, Green, Blue, and Luma, see Tetrachromacy - http://en.wikipedia.org/wiki/Tetrachromacy )

No matter how hard you work, there will be "something wrong" with it and room for improvement, at the very least for someone somewhere.

And this is one reason why there are so many shading models.

Because of all this a good artist always ends up cheating the levels of light and light response on environments to some degree to attain a "good enough" result (its never perfect), just give them access to fiddle with the settings and cheat their way to pleasing results.
> 1 votes

---
Tags: opengl, shading
---


# Question
Title: Make square walk by rotating around corners
I in the very beginning of making a small game, and I'm having some problems getting the basic movement of my character.

My character is a square that can be moved by rotating around a corner. The user chooses what corner to rotate around by pressing a button. Here is the (malfunctioning) code I've come up with this far(Java and slick2d):

```
    // square is an org.newdawn.slick.Image and is rendered by calling square.draw()

    @Override
    public void update(GameContainer container, int delta) throws SlickException {
        Input input = container.getInput();
        if (input.isKeyDown(Input.KEY_W))
        {
            square.setCenterOfRotation(0, 0);
            square.setRotation(square.getRotation() + 1);
        }
        else if (input.isKeyDown(Input.KEY_E))
        {
            square.setCenterOfRotation(square.getWidth(), 0);
            square.setRotation(square.getRotation() + 1);
        }
        else if (input.isKeyDown(Input.KEY_S))
        {
            square.setCenterOfRotation(0, square.getHeight());
            square.setRotation(square.getRotation() + 1);
        }
        else if (input.isKeyDown(Input.KEY_D))
        {
            square.setCenterOfRotation(square.getWidth(), square.getHeight());
            square.setRotation(square.getRotation() + 1);
        }
    }

```

This will rotate the square correctly, but when I switch rotation direction, the square jumps two times its lenght to the side I switched to. I think the problem is that I never really move the square, just rotate it away from its original position. I think this will also make collision detection difficult.

How would I prevent this 'jumping', and how will I later do collision detection on the image? Or asked in another way, how should I be doing the 'rotation walking'?

# Answer
Im not sure this works 100% but here is an idea to get you started. Let your square have x,y as center and r as its current rotation value. Let dx and dy be the displacement from center to one corner of the square when r is 0;

On rotate-moving the square on the said corner:

First get the corner's position:

```
 cx = x + rotated(dx, r);
 cy = y + rotated(dy, r);

```

Find the new correct center location after rotation dr:

```
 x = cx + rotated(-dx, r + dr);
 y = cy + rotated(-dy, r + dr);

```

See http://en.wikipedia.org/wiki/Rotation\_matrix for implementation of rotated.
> 1 votes

# Answer
Based on user55565's answer, I did some reading on rotation matrices and took his main idea and did some paper sketching. In the end I came up with the class below, which works.

The basic idea is to reference the position of the square by its center coordinates. When you want to rotate it, you follow these steps:

1. Calculate the current(before the additional rotation) position of the corner you want to rotate around, relative to the center (so the center is the origin). I do this by finding the relative position of the corner without rotation, and then apply a rotation matrix.
2. Find the current position of the center relative to the corner (so the corner is the origin).
3. Rotate the `center-relative-to-corner` coordinates around its origin (the corner)
4. Calculate the new center coordinates relative to the old (`corner-relative-to-old-center + new-center-relative-to-corner`) and add this to the old center, so you get the new absolute center coordinates(`old-center-absolute + new-center-relative-to-old-center`)

Here is my java implementation, using the jama Matrix library:

```
public class Square
{

    private final Image image;

    /** The offset from center to anchor point **/
    private final float xOffset;
    private final float yOffset;

    /** The center coordinates **/
    private Matrix center;

    public Square(Image image, float x, float y)
    {
        this.image = image;

        this.xOffset = image.getWidth()/2.0f;
        this.yOffset = image.getHeight()/2.0f;

        this.center = new Matrix(new double[][]{{ x },
                                                { y }});
    }

    public void draw()
    {
        image.draw((float)center.get(0, 0)-xOffset, (float)center.get(1,0)-yOffset);
    }

    public void rotate(float degrees, Corner corner)
    {
        /** Step 1 **/
        // Corner position relative to center (center is origo)
        Matrix cornerPos;
        switch (corner)
        {
            case TOP_LEFT:
                cornerPos = new Matrix(new double[][]{{ -xOffset },
                                                 { -yOffset }});
                break;
            case TOP_RIGHT:
                cornerPos = new Matrix(new double[][]{{ +xOffset },
                                                 { -yOffset }});
                break;
            case BOTTOM_LEFT:
                cornerPos = new Matrix(new double[][]{{ -xOffset },
                                                 { +yOffset }});
                break;
            case BOTTOM_RIGHT:
                cornerPos = new Matrix(new double[][]{{ +xOffset },
                                                 { +yOffset }});
                break;
            default:
                return;
        }
        // Compensate for existing rotation
        cornerPos = getRotationMatrix(image.getRotation()).times(cornerPos);

        /** Step 2 **/
        // Center position relative to corner (corner is origo)
        Matrix centerPos = new Matrix(new double[][]{{ 0 },
                                                     { 0 }}).minusEquals(cornerPos);

        /** Step 3 **/
        centerPos = getRotationMatrix(degrees).times(centerPos);

        /** Step 4 **/
        // Make centerPos be relative to old center
        this.center = this.center.plus(cornerPos.plus(centerPos));

        // Rotate the actual image
        image.setCenterOfRotation(xOffset, yOffset);
        image.rotate(degrees);
    }

    public Matrix getRotationMatrix(float degrees)
    {
        double radians = Math.toRadians(degrees);
        double cos = Math.cos(radians);
        double sin = Math.sin(radians);
        return new Matrix(new double[][]{{ cos, -sin },
                                         { sin,  cos }});
    }

    public static enum Corner
    {
        TOP_LEFT,
        TOP_RIGHT,
        BOTTOM_LEFT,
        BOTTOM_RIGHT;
    }

```
> 0 votes

---
Tags: java, rotation, movement, slick
---


title: Help finding time of collision

text:
# Question
Title: Help finding time of collision
I am making a simple game right now and am struggling with collision response. My goal is to someday be able to turn it into a 2D platformer but I have a long way to go. I am currently making this in JavaScript and using the canvas element so (0,0) is in the top left and positive X is to the right and positive Y is down.

I read a helpful post on StackExchange that got me started on this but I can't seem to get the algorithm 100% correct. How to deal with corner collisions in 2D?

I can detect the collision fine but I can't seem to get the response right. The goal is to detect which side the player hit first since minimum displacement doesn't always work. The X response seems to work fine but the Y only works when I am far from the corners. Here is a picture showing what happens

Here is the code

```
var bx = box.x;
var by = box.y;
var bw = box.width;
var bh = box.height;

var boxCenterX = bx + (bw/2);
var boxCenterY = by + (bh/2);

var playerCenterX = player.x + player.xvel + (player.width/2);
var playerCenterY = player.y + player.yvel + (player.height/2);

//left = negative and right = positve, 0 = middle
var distanceXin = playerCenterX - boxCenterX;
var distanceYin = playerCenterY - boxCenterY;

var distanceWidth = Math.abs(distanceXin);
var distanceHeight = Math.abs(distanceYin);

var halfWidths = (bw/2) + (player.width/2);
var halfHeights = (bh/2) + (player.height/2);

if(distanceWidth < halfWidths){
    //xcollision
    if(distanceHeight < halfHeights){
            //ycollision
            if(player.xvel == 0){
                    //adjust y
                    if(distanceYin > 0){
                            //bottom
                            player.y = by + bh;
                            player.yvel = 0;
                    }else{
                            player.y = by - player.height;
                            player.yvel = 0;
                    }
            }else if(player.yvel == 0){
                    //adjust x
                    if(distanceXin > 0){
                            //right
                            player.x = bx + bw;
                            player.xvel = 0;
                    }else{
                            //left
                            player.x = bx - player.width;
                            player.xvel = 0;
                    }
            }else{
                    var yTime = distanceYin / player.yvel;
                    var xTime = distanceXin / player.xvel;

                    if(xTime < yTime){
                            //adjust the x it collided first
                            if(distanceXin > 0){
                                    //right
                                    player.x = bx + bw;
                                    player.xvel = 0;
                            }else{
                                    //left
                                    player.x = bx - player.width;
                                    player.xvel = 0;
                            }
                    }else{
                            //adjust the y it collided first
                            if(distanceYin > 0){
                                    //bottom
                                    player.y = by + bh;
                                    player.yvel = 0;
                            }else{
                                    player.y = by - player.height;
                                    player.yvel = 0;
                            }
                    }
            }
      }
}

```

And here is a JSFiddle if you would like to see the problem yourself. http://jsfiddle.net/dMumU/

To recreate this move the player to here

And press up and left at the same time. The player will jump to the right for some reason.

Any advice? I know I am close but I can't seem to get xTime and yTime to equal what I want every time.

# Answer
> 2 votes
You are not using the right variable to perform the collision time calculation. `distanceXin` is the distance between the two objects’ **centres**, whereas what you actually want is the distance between the two objects’ **edges**.

Also, your code can be shortened and simplified a lot. Here is how I’d rewrite it:

```
var boxCenterX = box.x + (box.width / 2);
var boxCenterY = box.y + (box.height / 2);

var playerCenterX = player.x + player.xvel + (player.width / 2);
var playerCenterY = player.y + player.yvel + (player.height / 2);

// left = negative and right = positve, 0 = middle
var deltaCenterX = playerCenterX - boxCenterX;
var deltaCenterY = playerCenterY - boxCenterY;

// outside object = positive and inside object = negative
var deltaEdgeX = Math.abs(deltaCenterX) - (box.width + player.width) / 2;
var deltaEdgeY = Math.abs(deltaCenterY) - (box.height + player.height) / 2;

if (deltaEdgeX < 0 && deltaEdgeY < 0)
{
    if (deltaEdgeX * Math.abs(player.yvel) > deltaEdgeY * Math.abs(player.xvel))
    {
        // adjust the x it collided first
        player.x = box.x + (deltaCenterX > 0 ? box.width : -player.width);
        player.xvel = 0;
    }
    else
    {
        // adjust the y it collided first
        player.y = box.y + (deltaCenterY > 0 ? box.height : -player.height);
        player.yvel = 0;
    }
}

```

I’m afraid I must have done something wrong with your jsfiddle but this example should work: http://jsfiddle.net/4zh0aytd/

# Answer
> 0 votes
The error comes from `yTime` and `xTime`. Since you are using a rectangle that is wider than taller, your `xTime` is always greater than your `yTime`. This is way when colliding in the x directions it works, and when colliding in the y directions, the wrong thing happens. You can test this by swapping the width and height dimensions of the box, and the error will be just the opposite then.

You should be comparing how far the player is penetrating into the box's x space, with how far the player is penetrating into the box's y space; then based off whichever is great, adjust the player accordingly. I think this was your original intent.

Try replacing:

```
if(xTime < yTime){

```

with

```
if (halfWidths - distanceWidth < halfHeights - distanceHeight) {

```

---
Tags: 2d, collision-detection, response
---


title: Fragment Shader output type error

text:
# Question
Title: Fragment Shader output type error
StackExchange!

I've been working with opengl for a bit and I'm trying to finally load the shaders instead of having them inline. I'm having a ton of issues, though. As soon as I solve one, another pops up. Now, the issue is glGetProgramInfoLog reporting "Fragment Shader output type error." I thought it might be caused by the old graphics card - Intel Graphics 300, but it was working when it was inline (directly as a const char \*). Does anyone know what this might mean, and how to solve this? Thanks in advance!

Vertex Shader:

```
#version 400 compatibility

layout (location = 0) in vec3 vertexPosition;

uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;

void main () {
    gl_Position = Projection * View * Model * vec4(vertexPosition, 1.0);
}

```

Fragment Shader:

```
#version 330

layout(location = 0) out vec4 fragColor;

void main()
{
    fragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

```

Shader Loading Code:

```
GLuint getShaders(const char *vertexpath, const char *fragmentpath) {

    printf("****************** Loading Shaders ******************\nVertex: %s\nFragment: %s\n\n", vertexpath, fragmentpath);
    std::string VertexShaderCode;
    std::ifstream VertexShaderStream(vertexpath, std::ios::in);
    if (VertexShaderStream.is_open()){
        std::string Line = "";
        while (getline(VertexShaderStream, Line))
            VertexShaderCode += "\n" + Line;
        VertexShaderStream.close();
    }
    else{
        printf("Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n", vertexpath);
        getchar();
        return 0;
    }

    std::string FragShaderCode;
    std::ifstream FragShaderStream(fragmentpath, std::ios::in);
    if (FragShaderStream.is_open()){
        std::string Line = "";
        while (getline(FragShaderStream, Line))
            FragShaderCode += "\n" + Line;
        FragShaderStream.close();
    }

    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    char const * VertexSourcePointer = VertexShaderCode.c_str();
    glShaderSource(vs, 1, &VertexSourcePointer, NULL);
    glCompileShader(vs);

    GLint logSize = 0;
    glGetShaderiv(vs, GL_INFO_LOG_LENGTH, &logSize);
    printf("Size: %i\n", logSize);

    GLint isCompiled = 0;
    glGetShaderiv(vs, GL_COMPILE_STATUS, &isCompiled);
    if (isCompiled == GL_FALSE) {
        GLint maxLength = 0;
        glGetShaderiv(vs, GL_INFO_LOG_LENGTH, &maxLength);

        // The maxLength includes the NULL character
        std::vector<GLchar> errorLog(maxLength);
        glGetShaderInfoLog(vs, maxLength, &maxLength, &errorLog[0]);

        printf("Vertex Shader Error Report:\nSize: %i\n%s\n----------------------------\n", logSize, errorLog);

        // Exit with failure.
        glDeleteShader(vs); // Don't leak the shader.
        return 0;
    }

    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    char const * FragSourcePointer = FragShaderCode.c_str();
    glShaderSource(fs, 1, &FragSourcePointer, NULL);
    glCompileShader(fs);

    logSize = 0;
    std::string shaderInfo;
    glGetShaderiv(fs, GL_INFO_LOG_LENGTH, &logSize);
    printf("Size: %i\n", logSize);

    isCompiled = 0;
    glGetShaderiv(fs, GL_COMPILE_STATUS, &isCompiled);
    if (isCompiled == GL_FALSE) {
        GLint maxLength = 0;
        glGetShaderiv(fs, GL_INFO_LOG_LENGTH, &maxLength);

        // The maxLength includes the NULL character
        std::vector<GLchar> errorLog(maxLength);
        glGetShaderInfoLog(fs, maxLength, &maxLength, &errorLog[0]);

        printf("Fragment Shader Error Report:\nSize: %i\n%s\n----------------------------\n", logSize, errorLog);

        // Exit with failure.
        glDeleteShader(fs); // Don't leak the shader.
        return 0;
    }

    GLuint program = glCreateProgram();
    glAttachShader(program, fs);
    glAttachShader(program, vs);
    glLinkProgram(program);

    GLint isLinked = 0;
    glGetProgramiv(program, GL_LINK_STATUS, &isLinked);
    if (isLinked == GL_FALSE) {
        GLint maxLength = 0;
        glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);

        //The maxLength includes the NULL character
        std::vector<GLchar> infoLog(maxLength);
        glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]);

        //The program is useless now. So delete it.
        glDeleteProgram(program);

        printf("Program Error Report:\n%s\n----------------------------\n", infoLog);

        return 0;
    }

    glDeleteShader(vs);
    glDeleteShader(fs);

    return program;
}

```

# Answer
The issue was with the loading. I'm not sure what exactly the problem was, because I changed the code significantly, but it's working now.

EDIT Current loading code:

```
GLuint getShaders(const char *vertexpath, const char *fragmentpath) {

printf("****************** Loading Shaders ******************\nVertex: %s\nFragment: %s\n\n", vertexpath, fragmentpath);
std::string VertexShaderCode;
std::ifstream VertexShaderStream(vertexpath, std::ios::in);
if (VertexShaderStream.is_open()){
    std::string Line = "";
    while (getline(VertexShaderStream, Line))
        VertexShaderCode += "\n" + Line;
    VertexShaderStream.close();
}
else{
    printf("Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n", vertexpath);
    getchar();
    return 0;
}

// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragmentpath, std::ios::in);
if (FragmentShaderStream.is_open()){
    std::string Line = "";
    while (getline(FragmentShaderStream, Line))
        FragmentShaderCode += "\n" + Line;
    FragmentShaderStream.close();
}

GLuint vs = glCreateShader(GL_VERTEX_SHADER);
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(vs, 1, &VertexSourcePointer, NULL);
glCompileShader(vs);

GLint Result = GL_FALSE;
int InfoLogLength;

// Check Vertex Shader
glGetShaderiv(vs, GL_COMPILE_STATUS, &Result);
glGetShaderiv(vs, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0){
    std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1);
    glGetShaderInfoLog(vs, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
    printf("%s\n", &VertexShaderErrorMessage[0]);
}

GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
char const * FragSourcePointer = FragmentShaderCode.c_str();
glShaderSource(fs, 1, &FragSourcePointer, NULL);
glCompileShader(fs);

// Check Fragment Shader
glGetShaderiv(fs, GL_COMPILE_STATUS, &Result);
glGetShaderiv(fs, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0){
    std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1);
    glGetShaderInfoLog(fs, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
    printf("%s\n", &FragmentShaderErrorMessage[0]);
}

GLuint program = glCreateProgram();
glAttachShader(program, fs);
glAttachShader(program, vs);
glLinkProgram(program);

GLint isLinked = 0;
glGetProgramiv(program, GL_LINK_STATUS, &isLinked);
if (isLinked == GL_FALSE) {
    GLint maxLength = 0;
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);

    //The maxLength includes the NULL character
    std::vector<GLchar> infoLog(maxLength);
    glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]);

    //The program is useless now. So delete it.
    glDeleteProgram(program);

    printf("Program Error Report:\n%s\n----------------------------\n", infoLog);

    return 0;
}

glDeleteShader(vs);
glDeleteShader(fs);

return program;
}

```
> 1 votes

---
Tags: opengl, shaders, glsl, fragment-shader, vertex
---


title: change animations when touch sprites

text:
# Question
Title: change animations when touch sprites
In the following function I want to change the animation when I touch on the button. But the game crash and exit. What's wrong with this code ?

```
 bool GameScene::onTouchBegan(cocos2d::Touch *touch ,cocos2d::Event *event)
{
    Point touchPoint = Director::sharedDirector()->convertToGL(touch->getStartLocationInView());
    touchPoint = blueButton->convertToNodeSpace(touchPoint);

    Rect *blueBottomRect = new Rect(blueButton->getOffsetPosition().x
        , blueButton->getOffsetPosition().y
        , blueButton->getTextureRect().size.width
        , blueButton->getTextureRect().size.height);
    if (blueBottomRect->containsPoint(touchPoint))
    {
        CCLOG("Blue Touched!!!!!!!!!!!!!!!!!!");

        auto blueBody = Sprite::create("body1.png");
        blueBody->setPosition(Point(visibleSize.width / 2 , +220));

        Vector<SpriteFrame*> animFrames;

        animFrames.reserve(7);
        animFrames.pushBack(SpriteFrame::create("body1.png", Rect(0, 0, 99, 153)));
        animFrames.pushBack(SpriteFrame::create("body2.png", Rect(0, 0, 99, 153)));
        animFrames.pushBack(SpriteFrame::create("body3.png", Rect(0, 0, 99, 153)));
        animFrames.pushBack(SpriteFrame::create("body4.png", Rect(0, 0, 99, 153)));
        animFrames.pushBack(SpriteFrame::create("body5.png", Rect(0, 0, 99, 153)));
        animFrames.pushBack(SpriteFrame::create("body6.png", Rect(0, 0, 99, 153)));
        animFrames.pushBack(SpriteFrame::create("body7.png", Rect(0, 0, 99, 153)));

        Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.09f);
        Animate* animate = Animate::create(animation);

        blueBody->runAction(RepeatForever::create(animate));
        this->addChild(blueBody,100);
        redBody->removeFromParentAndCleanup(true);

    }

    Point touchPoint2 = Director::sharedDirector()->convertToGL(touch->getStartLocationInView());
    touchPoint2 = redButton->convertToNodeSpace(touchPoint2);

    Rect *redBottomRect = new Rect(redButton->getOffsetPosition().x
        , redButton->getOffsetPosition().y
        , redButton->getTextureRect().size.width
        , redButton->getTextureRect().size.height);
    if (redBottomRect->containsPoint(touchPoint2))
    {
        CCLOG("Red Touched!!!!!!!!!!!!!!!!!!");

        auto redBody = Sprite::create("RedBody/bodyRed1.png");
        redBody->setPosition(Point(visibleSize.width / 2 , +220));

        Vector<SpriteFrame*> animFrames2;

        animFrames2.reserve(7);
        animFrames2.pushBack(SpriteFrame::create("RedBody/bodyRed1.png", Rect(0, 0, 99, 153)));
        animFrames2.pushBack(SpriteFrame::create("RedBody/bodyRed2.png", Rect(0, 0, 99, 153)));
        animFrames2.pushBack(SpriteFrame::create("RedBody/bodyRed3.png", Rect(0, 0, 99, 153)));
        animFrames2.pushBack(SpriteFrame::create("RedBody/bodyRed4.png", Rect(0, 0, 99, 153)));
        animFrames2.pushBack(SpriteFrame::create("RedBody/bodyRed5.png", Rect(0, 0, 99, 153)));
        animFrames2.pushBack(SpriteFrame::create("RedBody/bodyRed6.png", Rect(0, 0, 99, 153)));
        animFrames2.pushBack(SpriteFrame::create("RedBody/bodyRed7.png", Rect(0, 0, 99, 153)));

        Animation* animation2 = Animation::createWithSpriteFrames(animFrames2, 0.09f);
        Animate* animate2 = Animate::create(animation2);

        redBody->runAction(RepeatForever::create(animate2));
        this->addChild(redBody,100);
        blueBody->removeFromParentAndCleanup(true);

    }

    return true;
}

```

# Answer
In cocos2d you need first to stop all running action of a node in order to be able to remove that node.

So I think you forget to stop the running action and you can fix it as below:

```
redBody->stopAllActions();
redBody->removeFromParentAndCleanup(true);

```

and

```
blueBody->stopAllActions();
blueBody->removeFromParentAndCleanup(true);

```

Hope It helps.
> 0 votes

---
Tags: c++, cocos2d-x
---


title: 2D games and modern OpenGL

text:
# Question
Title: 2D games and modern OpenGL
### Preconcepts

Ok, so what I've gathered so far is this:

* don't use fixed pipeline (deprecated or going to be deprecated)
* vbos store "object models" (n vertex data, mostly)
* vaos describe how data is laid down so that draw calls know what part of each vbo is for what kind of vertex information (one vao can refer to multiple vbos, the opposite is kinda difficult)
* each draw call also sends vertex data to shaders

### How I see 3D (optional)

Given these informations, I can see how drawing 3D complicated objects is very nice with modern OpenGL. You basically load a bunch of object models (probably from Blender or other similar software) into VBOs with local coordinates, and then you simply provide for each instance of an object a different shader parameter (offset) to draw to world space.

### Problem/question

In 2D problems and priorities are completely different, though. You don't draw much complex objects, you don't need complicated projection matrixes and whatnot and shaders are much simpler.

What would be the best way to draw frequently (really frequently, basically every frame) changing geometry with modern OpenGL?

In the following paragraph you can see some ideas of problems (the circle and rectangle problem), that better identify the kind of changes I'm interested in.

### My attempts (optional)

So, I began to think how I would deal with drawing basic 2D geometry on the screen:

* a square: load a `[(1, 0), (1, 1), (0, 1), (0, 0)]` VBO for the geometry of a square in local space, then provide the shader with the actual width of the square and world coordinates and color informations

cools, looks easy. Let's move to a circle:

* a circle: triangle fan with... eh. how much precision (number of vertexes)? for small circles precision must be small and for bug circles precision must be high. Clearly loading 1 VBO cannot possibly fit all cases. What if I need to add precision because a circle is resized to be bigger?

Less cool. Let's move to something slightly easier, a rectangle:

* a rectangle: eh. there's no "general rectangle geometry". You just have a width/height proportion and that's it, but each rectangle is probably different if the size changes.

As you can see, things go downhill from there. Especially with complex polygons and whatnot.

### No code policy :P

I just need an overview of the idea, no code is necessary, especially C or C++ code. Just say stuff like: "make a VBO with this vertex data, and then bind it, ...".

# Answer
**Your main question** seems to be:

> What would be the best way to draw frequently (really frequently, basically every frame) changing geometry with modern OpenGL?

In most ways, there's no big difference between 2d and 3d OpenGL. The graphics pipeline has that one extra coordinate, Z, which won't be used as much in 2d, but that's about it.

There's a few ways to change the geometry on each draw.

* You can push new CPU-provided vertexes every frame. (See https://stackoverflow.com/questions/14155615/opengl-updating-vertex-buffer-with-glbufferdata for some notes on reusing buffers.)
* You can draw different portions of an existing buffer, with `glDrawArrays(mode, first, count)`. If the animation loops, maybe you can put the precomputed frames with the different vertex lists in one big buffer, and draw the appropriate portion of the buffer each frame.
* You can influence the vertex list with some other data, like a uniform array, or a texture. In your vertex shader, read this data and apply it appropriately. These are just other idioms for presenting data to the GPU, and probably won't have much difference in performance.
* If you have many instances of the same geometry (possibly influenced by attributes), then `glDrawElementsInstanced()` may be useful
* You can influence the vertex list algorithmically in the vertex, geometry, or tessellation shaders. If the animation can be described mathematically, you might be able to keep the same vertex list, and change just a few shader uniforms each frame.

And perhaps your animation might be expressed as pure textures, with all animation done pixel by pixel by the cpu, or pre rendered from disk.

On the whole, I'd say, "Computers are fast, make it work the easiest way you can, which is probably by setting fresh CPU-made vertexes every frame. Then, see if that's good enough. Profile the battery/CPU usage first, memory footprint second."

**Your other question**, paraphrased, "What's a good way to draw circles and rectangles?"

Circles.

* With tessellation shaders (or geometry shaders) you *could* make your geometry dynamic.
* You could draw squares, and in your fragment shader only opaque (alpha = 1.0) within a radius, and transparent (alpha = 0.0) outside the radius. Then it's pixel perfect every time. (Make your square vertexes -1 to +1, and in fragment shader something like, `outColor.a = dot(coord.xy, coord.xy) < 1.0 ? 1.0 : 0.0;`. Could also smooth the edge a little, would look nice there...)
* You could just always use, say, a 120-triangle fan. Probably good enough.

Rectangles.

* I think you answered your own question, on that one. What you suggest will work fine!
> 5 votes

# Answer
I can't say to be expert of this subject, and in my game project(s) I have concentrated more on 3D side, so my 2D side is pretty simple generally using things made for 3D side; and obviously, my perspective is at gaming side, so my 2D graphics is more about blitting sprites than geometry. From that perspective,

1) Squares and rectangles are pretty easy. I have just single 1x1 box in a VBO which I use to blit everything. I pass MVP matrices to shader with this "unit box", and I have combined it with additional scaling to scale the box to right dimensions - as you know, you can have different x and y scale.

For my purposes, I have been thinking to move from using "unit box" to some sort of particle engine to blit 2D sprites, but that's another story.

2) I haven't work much with circles, I just use fixed VBOs with specific number of vertices. But I could imagine that I could make some stride tweaking to affect to the number of vertices drawn for the circle.

When connecting VBO data to shader attributes, I use glVertexAttribPointer. It has stride parameter meant to be used for interleaved data (which I use). But it might be possible to use it like this:

```
glVertexAttribPointer(..., n * sizeof(VERTEX_DATA), ...);

```

...to pick every nth vertex from the buffer, thus affecting to the number of vertices drawn for the circle. I could create several VAOs having the same VBO with different stride affecting to number of vertex drawn for circle. I haven't tried that, thought.

In general, yes, working with VBOs and such make CPU-side tweaking bit more complex, why I have been studying different things to make tweaking at GPU side (shaders). Still, according to this article, using VBOs is more efficient on modern hardware even if you need lots of CPU side "intervention":

http://www.quelsolaar.com/opengl\_performance.txt

Hope this helps you a bit to design & decide your directions.
> 5 votes

---
Tags: opengl, 2d, vbo, vao
---


# Question
Title: how to remove game objects after on overlap in LIBGDX game
I have gold stars in my game that give score to game hero if the hero overlap with the star. What I want is to remove star once it overlap with hero object. I give score by checking overlap with this code

```
public void scorecount(Hero myhero){

            if (!star.isScored() && Intersector.overlaps(myhero.getBoundingBalloon(), star.getStarCircle()))
    {

                addScore(1); // give one plus always
  star.setScored(true);

AssetLoader.coin.play();

}

```

Now once I give score and setScore true , i want to remove star. How can I do that? I tried for setvisible method but I dont know how to use it. Because just Calling star.setVisible() ask to create this method in star class. then in star class I dont know what should be given inside this method body.

# Answer
You could use an `ArrayList` to store all your stars in. When collision is detected you remove star from array so the star is no longer updated.

So :

**create** :

```
ArrayList <Star> stars= new ArrayList<Star>();

```

**add the stars** :

```
stars.add (new Star (param1, param2));

```

**update** :

```
    for (int i = 0; i < stars.size(); i++) {
       star.get(i).update (param1, param2);
    }

        for (int i = 0; i < stars.size(); i++) {
          if (player.overlaps(stars.get(i)) {
              // remove star from arraylist
              stars.remove(i);
              // another approach would be not to remove the star, but to respawn it
              // on a different position; it depends what your game logic require
              stars.get(i).respawn (param1, param2);
         }
            }

```
> 1 votes

---
Tags: java, android, game-design, libgdx
---


# Question
Title: Drawing shapes and images in libgdx dialog
I am currently working on a dialog window for my android game using libgdx. This dialog window contains a collection of labels and buttons, but should also contain an image. The image represents the "remaining health indicator", i.e. an empty indicator with a symbol indicating the health of the player. This indicator has to be filled with a colored rectangle representing the remaining amount of health (see screenshot below).

In order to render this on a dialog of libgdx, I have to draw an image and a colored rectangle (the red rectangle indicating the real amount of remaining health). I know that the dialog supports the rendering of images, but I don't know how to first draw the rectangle.

This is the code I have so far:

```
public FuelFacilityDialog(GameWorld world, GuiComponent gui) { super("Health check", gui.defaultSkin);

    this.world = world;
    this.gui = gui;

    setModal(true);
    setMovable(false);
    setResizable(false);

    Image healthIndicator = new Image();
    Button button1   = new TextButton("heal", gui.defaultSkin);
    Button button4   = new TextButton("Exit", gui.defaultSkin);

    healthIndicator.setDrawable(new TextureRegionDrawable(AssetLoader.healthIndicatorV));
    healthIndicator.setScaling(Scaling.fit);
    setObject(button1, true);
    setObject(button4, false);

    Table imageTable = new Table();
    Table buttonTable = new Table();

    imageTable.add(healthIndicator).width(100).height(200);
    buttonTable.add(button1).width(100).height(50).expandY();

    this.getContentTable().padTop(20);
    this.getContentTable().padBottom(20);
    this.getContentTable().add(imageTable);
    this.getContentTable().add(buttonTable).height(200);
    getButtonTable().add(button2);
}

```

# Answer
I have found the answer for my problem. In order to draw an image and a shape, one can use a pixmap. It is possible to first create a pixmap on which you draw a rectangle. Then, you create another pixmap on which you draw the image. Both pixmap then can be combined by drawing one pixmap onto the other.

This is the code I use to build an image containing a rectangle indicating the actual health level and drawing the indicator image on top of it.

```
private Image getHealthIndicatorImage() {
        Image indicatorImage = new Image();
        Pixmap healthIndicator = new Pixmap(AssetLoader.healthIndicatorV);
        Pixmap healthLevel = new Pixmap(healthIndicator.getWidth(), healthIndicator.getHeight(), Format.RGBA8888);

        healthLevel.setColor(Config.InstrumentPanel.healthInstrumentColor1);
        healthLevel.fillRectangle(0, 0, 50, 50);
        healthLevel.drawPixmap(healthIndicator, 0, 0);

        indicatorImage.setDrawable(new TextureRegionDrawable(new TextureRegion(new Texture(healthLevel))));
        indicatorImage.setScaling(Scaling.fit);

        return indicatorImage;
    }

```
> 1 votes

---
Tags: java, android, libgdx, gui
---


title: XNA Weird Alpha Blending

text:
# Question
Title: XNA Weird Alpha Blending
I recently implemented a prelighting renderer for my XNA voxel engine, but there is now a weird alpha blending glitch. When I render to the light map, I set the graphics device's blend state to additive (though in the pixel shaders for each light I output an opaque color). When I finally render the world, I set the device's blend state to opaque, I only deal with the RGB components of colors in the shaders, and I again output an opaque color. However, the light map and the final rendering both somehow have transparency.

**Edit:** I believe the problem with the final rendering is caused by the light map's transparency issues. If a pixel appears to be semi-transparent in the light map, then it will appear as so in the final rendering because of how the final color is calculated.

Here is a picture of the rendered world (there is a blue directional light and a red point light at the player's position):

Here is a picture of the light map (different seed, but you get the idea):

Here is my directional light pixel shader (the point light one is similar, but \[obviously\] with point light calculations):

```
float4 PSFunc( VSOutput input ) : COLOR0
{
    // extract information
    float2 coords = GetTexCoords( input.LPosition );
    float4 normal = ( tex2D( normalSampler, coords ) - 0.5 ) * 2.0;

    // calculate the lighting value
    float3 lighting = clamp( -dot( normalize( lightDirection ), normal.xyz ), 0.0, 1.0 ) * lightColor;
    return float4( lighting, 1.0 );
}

```

Finally, here is my pixel shader that combines texture and lighting values:

```
float4 PSFunc( VSOutput input ) : COLOR0
{
    // extract lighting info (TPosition is the world position in the TEXCOORD0 channel)
    float2 coords = ProjectToScreen( input.TPosition ) + GetHalfPixel();
    float3 light = tex2D( lightSampler, coords );
    light += ambientColor; // ambientColor is a float3

    // calculate final color
    float3 tex = tex2D( spriteSampler, input.UV ).rgb;
    return float4( tex * diffuseColor * light, 1.0 );
}

```

**Note:** I do use the sprite batch to render the text, **but** I have a graphics state class that allows me to push and pop states (rasterizer, blend, depth-stencil, etc.), so I use that to preserve states when drawing with the sprite batch.

# Answer
I've found the error. When I render point lights, I use a light mesh placed where the light is. When I render directional lights, I cannot do this because there is no position so I need to render the entire world. For some reason having the blend state set to additive when doing this caused the transparency issues, so when I draw the directional lights I use an opaque blend state then switch back to additive. This works for now because I only have one directional light (the sun) and I only plan to use that one.

Here is a picture of the result now:
> 0 votes

---
Tags: xna
---


title: Adding SpriteFont in Monogame

text:
# Question
Title: Adding SpriteFont in Monogame
My question is probably something you guys have heard before - "How do you add SpriteFont's in Monogame's content manager?" The simple answer to this is, right click the 'Content' folder, go on 'Add New Item' and then you'll find it there. In my case however, there is no SpriteFont.

As far as my development environment goes, I am using Windows 7 and Visual Studio 2012. Upon getting Visual Studio, I installed MonoGame 3.2. My project is a MonoGame Windows Project (C#). As far as I can see, there are absolutely no options to add SpriteFont's to the MonoGame content manager. Right clicking the Content folder and going on Add New Item simply gets me this:

No sign of SpriteFont anywhere, whether I look under Visual C# Items or Online. What am I doing wrong?

The above is my content manager. If I go on Edit, New Item and then add my SpriteFont this way it will add, however the moment I go on Build, it will say 'MGCP has stopped responding'. This makes me think something is missing... A certain something called XNA Game Studio 4.0. I did some research and found a couple tutorials that tell you to install this, which makes me wonder if it is indeed needed. A friend of mine however is adamant that XNA Game Studio is not needed and that the only thing I need is VS 2012 and MonoGame.

Am I doing something wrong? Am I missing something? And is the answer to all my problems XNA Game Studio 4.0?

# Answer
You friend is wrong. The spritefont content template is part of XNA's additions to visual studio. Unfortunately they are not easy to add to VS2012.

According to this answer (https://gamedev.stackexchange.com/a/35413/19126), the workaround for adding them to 2012 also involves installing 2010 anyway, so you might as well just install and use that.

Here is another well-answered question discussing the process and linking to various resources. Good luck. How to generate Spritefonts for monogame
> 1 votes

---
Tags: c#, xna-4.0, monogame, visual-studio
---


title: Hero made of parts 2d rotation

text:
# Question
Title: Hero made of parts 2d rotation
I have a problem with rotation of my hero in 2D space. The hero is made of body parts such as: head, arms etc. Every part is a separate sprite. When I want to rotate the hero, I have to rotate all of its parts.

I know the hero position, and I save the parts positions as:

```
head = (heroPosition.x+20, heroPosition.y+20)

```

In other words I know the positions of all parts while the hero was not rotated. After rotation I know only the hero position and the rotation angle(Grades).

How can I calculate the new position for each part?

# Answer
This problem is called Forward Kinematics. To solve this problem in general, I recommend creating what is called a Kinematic Chain, or Kinematic Tree. To do this, you will need knowledge of a 2D rotation matrix, or transformation matrix.

A 2D 3x3 transformation matrix is defined as:

```
H = [xx, xy, tx;
     yx, yy, ty;
      0,  0,  1];

```

In this case, \[xx, yx\] represents the x axis of the transformation, \[xy, yy\] represents the y axis, and \[tx, ty\] represents the *translation* of the transformation. For instance, the transformation:

```
    H = [1, 0, 1;
         0, 1, 0.5;
         0, 0, 1];

```

translates a part 1 unit in the *x* direction, and *0.5* units in the y direction. To transform any vector, just pre-mulltiply it by the transformation matrix *H*. A special case of the transformation matrix is the rotation matrix. In 2D, a pure rotation can be represented as:

```
H = [cos(theta), -sin(theta), 0;
     sin(theta),  cos(theta), 0;
              0,           0, 1];

```

where *theta* is the rotation value in Radians.

Now, to implement a Kinematic tree, you just need to do this:

```
// Represents a rigid link in a kinematic chain
class Link
{
  public:
    // All links have exactly one or zero parent links.
    // The "root" of the tree has no parent (NULL)
    Link* parent;
    // All links can have as many children as needed
    std::vector<Link*> children;

    // Represents the transform from the parent link to
    // this link.
    Matrix3x3 localTransform;
    // Reprsents the transform from the world to this link.
    Matrix3x3 globalTransform;

    // Computes the global transform of this link with respect
    // to the world. Then computes the global transforms of all
    // children.
    void ComputeTransformsRecursive()
    {
       // If we're the root link, the global transform is the local transform.
       if(!parent) globalTransform = localTransform;
       else
       {
           // Otherwise, the global transform is the parent's global transform
           // times our transform (matrix multiplication)
           globalTransform = parent->globalTransform * localTransform;

           // Now recursively compute the global transform for each of the children
           for (Link* link : children)
           {
               link->ComputeTransformsRecursive();
           }
       }
    }

}

```

To build the kinematic tree for your character, you just do this:

```
// The body is the base link, and starts at (0, 0) with 0 rotation.
Link* bodyLink = new Link();
bodyLink->parent = NULL;
bodyLink->localTransform = Matrix3x3::Identity();

// The left arm, relative to the body, is 50 pixels to the right and 10 up,
// with no local rotation.
Link* leftArm = new Link();
leftArm->parent = bodyLink;
leftArm->localTransform = Matrix3x3::CreateTranslation(50, 10);
bodyLink.children.push_back(leftArm);

// The right arm is 50 right and 10 down.
Link* rightArm= new Link();
rightArm->parent = bodyLink;
rightArm->localTransform = Matrix3x3::CreateTranslation(50, -10);
bodyLink.children.push_back(rightArm);

// The head is 10 right and 0 down
Link* head = new Link();
head->parent = bodyLink;
head->localTransform = Matrix3x3::CreateTranslation(10, 0);
bodyLink.children.push_back(head);

```

You can rotate/translate the entire character just by moving around the body link:

```
bodyLink->localTransform.translation = Vector2(xPosition, yPosition);
bodyLink->localTransform.rotation = theta;

```

Then, to update, you just need to do this:

```
bodyLink->ComputeTransformsRecursive();

```

From there, you automatically get the global transforms (their rotations and translations):

```
Matrix3x3 headTransform     = head->globalTransform;
Matrix3x3 leftArmTransform  = leftArm->globalTransform;
Matrix3x3 rightArmTransform = rightArm->globalTransform;

```

You can also attach/detach nodes to different parts of the body to do things like make the character hold a gun, for instance.
> 3 votes

# Answer
You need to move each part to 0,0 then rotate them, then move them back. Without doing this they just rotate around 20 units fron your character
> 1 votes

# Answer
For each part, it need to have an offset to the hero location. Eg, +20, +20. Its correct position when hero rotation is r is heroPosition.x + rotated(offsetX, r) and same for y. See http://en.wikipedia.org/wiki/Rotation\_matrix for more info.
> 0 votes

---
Tags: c++, 2d, rotation, transformation
---


# Question
Title: Direct raycasting from moving point A and moving Point B
I am attempting to raycast from Point A to Point A (both moving points). I dont understand the comcept of raycasting (direction).

```
Update() {
    player = GameObject.FindGameObjectWithTag ("Player");
    //Debug.Log (player.transform.position + " " + transform.position);

    Vector3 direction = (player.transform.position - transform.position).normalized;
    Debug.Log (direction);
    Ray ray = new Ray (transform.position, direction);
    RaycastHit hit;

    Debug.DrawRay (transform.position, direction, Color.red);

    if(Physics.Raycast(ray, out hit, 3f)) {
        gameObject.renderer.material.color = Color.blue;
        //Debug.Log("OK");
    }
    else {
        gameObject.renderer.material.color = Color.white;
    }
}

```

The problem i have right now is that. When the player is below 0.88 on the Y Axis the enemy will turn blue. Else its white. Enemy doesnt turn blue when player is very close to enemy.

Thanks in advance

# Answer
The block of code you posted is working fine.

First of all, be sure your player has a 3D collider ( box, capsule, etc ) in it.

Second, be sure to change the material color in one spot only. If the color is blinking, maybe you're changing it in two different updates.

Third, I don't think it is the source of the problem, but Unity documentation encourage you to do physics things in FixedUpdate instead of Update.

If everything above is right and you are still having problems, provide a bit more details, so I can try to help you out.
> 0 votes

---
Tags: c#, unity, vector, raycasting
---