# Question
Title: Calculate the Intersection of Two Volumes
If you've ever played The Swapper, you'll have a good idea of what I'm asking about.

I need to check for, and isolate, areas of a rectangle that may intersect with either a circle or another rectangle. These selected areas will receive special properties, and the areas will be non-static, since the intersecting shapes themselves will also be dynamic. My first thought was to use raycasting detection, though I've only seen that in use with circles, or even ellipses.

**I'm curious if there's a method of using raycasting with a more rectangular approach, or if there's a totally different method already in use to accomplish this task.** I would like something more exact than checking in large chunks, and since I'm using SDL2 with a logical renderer size of 1920x1080, checking if each pixel is intersecting is out of the question, as it would slow things down past a playable speed. I already have a multi-shape collision function-template in place, and I could use that, though it only checks if sides or corners are intersecting; it does not compute the overlapping area, or even find the circle's secant line, though I can't imagine it would be overly complex to implement.

**TL;DR:** I need to find and isolate areas of a rectangle that may intersect with a circle or another rectangle without checking every single pixel on-screen.

# Answer
> 2 votes
You can do this by clipping one volume to that of another. The original question you asked actually falls under the category of boolean operations on volumes, and can get very complicated.

In your case you want to find an intersection, which is a fundamental boolean operation. Since you have the constraints of only rectangles and circles you're in luck! You can solve for the intersection of two convex solids in 2D with an algorithm called Sutherland-Hodgman clipping.

In order to use a clipping routine to find the intersecting area you will need to represent a circle as a discrete set of points. The more points your circle has the more smooth the arc is, but the more expensive each volume is to collide with. You'll have to tune how many vertices your circle approximation has. Note that you can render a circle as smooth as you like with a much lower-fidelity collision object underneath that remains invisible.

Here is an article I wrote on the topic of Sutherland-Hodgman clipping. The idea is to loop over the edges of one of your volumes and clip each edge inside the boundaries of all edges of another polygon.

Sutherland-Hodgman works by defining a few different cases of having two end-points of a line segment on either side of a plane (a line in 2D); here is the most relevant pseudo-code from the article:

```
// InFront = plane.Distance( point ) > 0.0f
// Behind  = plane.Distance( point ) < 0.0f

Vec2 p1, p2;
ClipPlane plane;

case p1 InFront and p2 InFront
  push p2
case p1 InFront and p2 Behind
  push intersection
case p1 Behind and p2 InFront
  push intersection
  push p2

```

This psuedo code gets applied to each segment of one volume for each plane of the other. As this code is run vertices are output into a new array, and they represent the boundary of your intersection. The intersection of two convex volumes is always a new convex volume. This means you can easily render the volume with a triangle fan, and collide it with other convex volumes with the Separating Axis Theorem.

---
Tags: c++, sdl, raycasting
---


# Question
Title: Unable to use Maya animation with scripts when imported to Unity
I am testing to import **Maya** animation over to **Unity**. I set up a simple cylinder with 2 bones and an IK handle. Made a simple animation where the cylinder bends and goes back to straight position over 24 frames.

Following that, I selected everything and baked, all bones,ik,(animation by selecting all at the graph editor) and even the cylinder. I saved the scene and then select all and export as FBX with animation and bake checked.

In unity imported it and at the preview able to see the animation. When I load the model into scene and play (after assigning the controller), able to see animation too.

But now when I try to script it and control the animation, nothing happens. Even to test, I tried the following under the Update method.

```
if(animation.isPlaying)
    Debug.Log("Animation Works");
else
   Debug.Log("Animation not working");

```

The bool doesn't even return true nor false. My animation is called "bend", thus just for try I did the following and nothing happens.

```
animation.Play("bend");

```

Can please advice based on my steps, am I missing something. Do I need to add the controller or is that an unnecessary step? Did I screw up on the Maya part or the Unity part. Thanks for help.

# Answer
Ok your first problem is that the code there is for Legacy animation, and you probably imported as the default which is Mecanim (actually, in comments we already determined that; just leaving this note here for future visitors). Unity has an older animation system that is still around for legacy reasons, but you shouldn't use that for future projects. However for reference you can switch between animation systems in the Rig tab of the model; there is a drop-down to switch between Humanoid and Generic rigs (both of which fall under the umbrella of Mecanim), or you can set to Legacy.

---

Anyway, at a high-level the way you use the new animation system is by setting up a bunch of animation states in an Animator controller, assign parameters to transition between those animation states, and then when your code passes values to the animator it will transition between animations. Whereas in Legacy the animations are attached to the model directly and your code plays animations by name, in Mecanim the animations are used in an Animator and the Animator is attached to the model. This indirection is the first thing to understand; it can seem a bit odd since the animation clips can be part of the model (ie. part of the fbx file that was imported) but this indirection also allows you to share animations from other models.

refer to http://docs.unity3d.com/Manual/AnimationParameters.html

Create a new Animator controller, and then open the Animator window to edit it. First click the + button in the lower-left to setup parameters you'll use (eg. a float called Speed). You can drag animation clips into the Animator (click the right arrow on a model asset to see the animation clips) and then right-click the animations to set transitions between them (eg. from Idle animation to Run animation when Speed is greater than 1). Finally select the model in the sene and drag the Animator asset to the animator slot in the Inspector.

At this point the code to trigger animations is pretty simple; Mecanim is designed to handle for you all the complex work of deciding which animation to play and transitioning between them. In your code you need a reference to the Animator component; there are a variety of ways to do that, one of the simplest being GetComponent (this is C# code):

```
private Animator _animator;

...

void Start() {
  _animator = GetComponent<Animator>();
}

```

Now passing values to the animator is simply done with commands like:

```
_animator.SetFloat("Speed", 1.5f);

```

or

```
_animator.SetBool("Jumping", true);

```

This might seem like a lot of rigamarole for just testing an arm bending, and well it is a lot for just that. However Mecanim was designed for the complex animations that happens in games, where you want a character to fluidly transition between a bunch of aniamtions. With animation clips set in the imported model, and animation states set in the Animator controller, there's very little your code needs to do to run the animations.
> 2 votes

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


# Question
Title: LibGDX - SpriteBatch's .draw() method requiring float[]
Please excuse my lack of knowledge with LibGDX, as I have just started learning it. I am going through some simple tutorials, and in one of them, I draw a string onto the screen like so:

```
// the following code is in the main file in the core project folder:

// this is in the create() method:
private SpriteBatch batch;
batch = new SpriteBatch();

// this is in the render() method:
batch.draw(batch, "Hello world", 200, 200);

```

I am getting an error saying: The method draw(texture, float\[\], int, int) in the type SpriteBatch is not applicable for the arguments (SpriteBatch, int, int)

So, LibGDX wants a float array to draw instead of a string?

Thanks in advance.

# Answer
> 2 votes
Well, I found my problem. I was using a bitmap font, and instead of using the SpriteBatch's .draw(), I was supposed to use the bitmap font's .draw(). Thanks for the help everyone.

# Answer
> 2 votes
You should follow the official libGDX setup instructions.

There's a section about `Using "Libgdx Setup"` where you execute a JAR file. This provides you with a GUI project builder, which will allow you to configure some options like:

* Project types (Android, desktop, iPhone, etc.)
* Advanced options (eg. IntelliJ project file)

Once you do this, you'll have working code which you can run.

You're misunderstanding the compiler error. It expects `Texture, float[], int, int` and you're passing in `batch, "Hello world", 200, 200` which is `SpriteBatch, String, int, int`. That's not right.

# Answer
> 2 votes
According to the API documentation for SpriteBatch there is no method signature for 'draw' that expects a 'SpriteBatch, String, int, int' parameter list. Logically it also makes no sense to pass a reference to the SpriteBatch to itself in its draw call.

If you are attempting to draw a string ("Hello world") to the screen then you will need to use a BitmapFont alongside the SpriteBatch. A useful reference link to the wiki here. A link to the BitmapFontTest class demonstrating how to use the BitmapFont class here.

If you feel confused or lost on how a certain section of libGDX works I strongly recommend browsing through the tests directory of the GitHub repository here. It's likely you'll find a test case showing how to use it.

# Answer
> 2 votes
What you are doing is mixing up a couple of different ways to make a draw call in LibGdx. This is the trouble with copy-pasting from tutorials, but I can tell exactly what is going on. There are two commons ways of making a draw call. One is from directly inside the render() method and is common in simple tutorials. The other way is to create a draw() method in another class like a Sprite that takes a spritebatch as an argument. You seem to be mixing these two styles.

You are trying to draw some type of object that knows how to draw strings, but you replaced that object reference with the spritebatch that you are supposed to be passing it. Replace the first batch in `batch.draw(batch, "Hello world", 200, 200);` with whatever that object is that you are trying to draw. It would help to be able to see more of your code.

---
Tags: java, libgdx, spritebatch
---


# Question
Title: How to move an image back and forth with javascript
I currently am trying to make a baseball game and have this code here: http://jsfiddle.net/769BK/ I have the `baseballX` set to a decrement, and then I try increasing the value using `baseballX++;` but it won't stop the `baseballX--;` after that so it stays in the same place. I need to somehow stop the `baseballX--;` and that way I can use `baseballX++;`

Thanks for any help at all!

# Answer
> 0 votes
You never tell your script to stop incrementing the position of the baseball. To do this, have a boolean as a flag as to whether to increase the baseball or not. An example of this would be

```
var flag = true;

if (flag)
{
    //do something, and eventually set flag to false
    flag = false;
}

else
{
    //do something else
}

```

In this instance, you would stop incrementing when the flag is false, and begin incrementing then. I would read this question even though it is in VB because it will help you understand the concept behind this behavior.

**EDIT**

What I mean when you start/stop the increment, is when you are changing the position of the ball. I have a fiddle showing what is happening. The main error you were getting was that you would move the baseballX back, then forward, then back, etc. I fixed this using the flag, and in your `throwBack` function, you reset `baseballX` to -350. Some pseudocode of what was happening is like:

```
while (true)
{
    pitch();//1st time: move the ball backwards; 2nd time: the ball's X is greater than -350, so move back until it is less
    if (ballX < -350)
    {
        throwBack();//1st time: resets the ball position to -350, and moves forward; 2nd time: the ball is below so move forward, rinse and repeat
    }
}

```

The flag enabled us to do

```
while (true)
{
    if (!baseballBack)
        pitch();//1st time: move the ball backwards; 2nd time: flag tells us to stop pitching
    if (ballX < -350 || baseballBack)
    {
        baseballBack = true;
        throwBack();//1st time: resets the ball position to -350, and moves forward; 2nd time: the flag is true, so continue to execute.
    }
}

```

# Answer
> 0 votes
You could do like so:

```
var baseballMoveBack = true;

function toggleMovement() {
    if (baseballMoveBack) baseballMoveBack = false;
    else baseballMoveBack = true;
}

function loop() {
    if (baseballMoveBack) baseballX--;
    else baseballX++;

    setTimeout(loop, 1);
}

```

First declaring a variable that tells us whether the ball should go back or forth. Then we make a function that will toggle the `baseballMoveBack` boolean. Last we have a loop that will increase or decrease `baseballX`.

Hope this helps!

---
Tags: 2d, javascript, html5, movement, html-canvas
---


# Question
Title: How to mimic the same fixed-size horizon as in this racing game?
I am trying to replicate the same horizon (buildings and sky) as in the image below:

As you can see, the player has advanced in a straight line, yet the horizon has still the same size:

This is my attempt using 3D, while it's *okay* when the player is on the start line:

It's not so great when the player advanced as much as in the image no. 2:

This is an overview of where the horizon buildings and sky are located:

Obviously this won't achieve such effect when one is close to it, so I've tried to scale up the horizon on all axes but the problem is that the buildings are too small depending where you look at them from.

**How can one mimic such rendering ?**

# Answer
The two easiest ways I can think to do this are to either maintain a fixed distance between the camera and the horizon geometry, or draw the horizon as a 2D sprite, with the latter most likely being easier.

I believe that the game you are mimicking was able to achieve this because it was not actually a 3D game, but a 2D game that simulated movement through a 3D space; a 2.5D game, if you will. For that reason, drawing the horizon at a perceived fixed 3D distance is easy, because the 2D asset always needs to be rendered to the same portion of the screen.

To render it as a 2D asset, the simplest way I can think of is to first separate out objects into three categories: objects that will never extend visually into the sky (the road, and ground), objects that will (tall cacti, the player maybe), and the horizon/sky. The drawing algorithm then becomes:

```
1. Draw anything that won't overlap the horizon.
2. Clear the depth buffer.
3. Draw the horizon to the top half of the screen.
4. Draw everything else.

```

There are definitely other ways to do it. If you can guarantee that the ground will not draw above the horizon line, you can skip the depth buffer clear.

In short, trying to get what you want using exclusively 3D objects is possible, but would probably overcomplicate things. Try rendering it in 2D first.
> 3 votes

# Answer
You need to cancel translation from camera transform when rendering skybox, then just draw box at 0, 0, 0.

When you set effect.View you need to use modified camera.View where: newView.\_41 = 0 newView.\_42 = 0 newView.\_43 = 0
> 2 votes

---
Tags: 3d, rendering, monogame
---


title: How does this game loop actually work?

text:
# Question
Title: How does this game loop actually work?
I read this playfulJS post, about ray-casting: http://www.playfuljs.com/a-first-person-engine-in-265-lines/

It looks really interested, so I decided to look at his javascript. I am no expert in javascript, so I quickly got lost.

It's the game loop "object" that really gets me. I simply don't understand how it works. From the code:

```
function GameLoop() {
        this.frame = this.frame.bind(this);
        this.lastTime = 0;
        this.callback = function() {};
      }

      GameLoop.prototype.start = function(callback) {
        this.callback = callback;
        requestAnimationFrame(this.frame);
      };

      GameLoop.prototype.frame = function(time) {
        var seconds = (time - this.lastTime) / 1000;
        this.lastTime = time;
        if (seconds < 0.2) this.callback(seconds);
        requestAnimationFrame(this.frame);
      };

var loop = new GameLoop();

      loop.start(function frame(seconds) {
        map.update(seconds);
        player.update(controls.states, map, seconds);
        camera.render(player, map);
      });

```

Now, what really confuses me here, is this bind stuff and how this actually loops.

I am guessing, that if less than 0.2 seconds have passed, since the last time the loop was run, it simply goes back to re-check the time. If more than 0.2 seconds have passed, it leaves the frame function, and executes the 3 lines in the loop.

But, if this is true, then how does the loop.start() get called again? And what on earth is the meaning of `this.frame = this.frame.bind(this);`?

I've looked up prototypes bind() but I really don't understand it.

# Answer
You're on the right track, but your guess is a bit backwards. The `start` prototype of `GameLoop` takes a callback function that represents the core update steps of the application; in this case, player and map updates, and drawing. The `frame` function will run this callback function if the time elapsed since the last frame is less than `0.2` seconds. I'm assuming that `requestAnimationFrame` is a higher level API call to refresh the window.

Now, `requestAnimationFrame` takes a callback which represents the function it should run as part of the window refresh. The writer of this code wanted this callback to be associated with a particular object, so that it could have access to internal variables such as `this.callback` and `this.lastTime`. In order to do that, the callback provided to `requestAnimationFrame` must be bound to a specific instance of `GameLoop`, and that is what `this.frame.bind(this)` accomplishes.

To put it another way, the call to `bind` establishes that the `this` object in the prototype `frame` function will refer to a specific instance of `GameLoop`; the one provided in the call to `bind`.
> 0 votes

---
Tags: javascript, game-loop
---


# Question
Title: What were the typical price range for a development kit?
A lot of these things are usually behind NDAs and tricky to gauge. Is there any information and ranges on how much these thing costs?

For example, the PS1 had the "Net Yaroze", which according to Wikipedia was: "For about $750 USD, the Net Yaroze (DTL-H300x) package would contain a special black-colored debugging PlayStation unit with documentation, software, and no regional lockout."

**So, what were the prices of some game development kits?**

P.S: This might make a good community wiki

# Answer
Historically, development kits have not been retail products. Sony's Net Yaroze program was an early anomaly.

Development studios were granted access to kits through the contractual agreements they established with the platform vendor (Nintendo, Sony, Microsoft, et cetera) or publisher; part of that agreement would typically include a licensing agreement to make use of the platform's development kits (either directly or via a publishing agreement). The details of those contracts are generally secret, and could vary with studio/publisher/platform/time/et cetera.

In some cases a studio would be granted a particular allotment of hardware for "free" as part of the deal. In some cases they could license (not purchase) additional devices for some fee.

While the specific costs could vary, the majority of such agreements were typically "boilerplate" in that regards and the effective prices of development kits tended to float in some range. For example, in 2007 the cost of a PS3 development kit was *halved* to about $10,000. The modern Wii U kit is rumored to cost $5,000.

It's basically a safe assumption that the kits would cost anywhere from $0 to $15,000, generally. This doesn't even include other fees involved in development; for example, back in the cartridge days you generally had to pay (Nintendo at least) to have your cartridges duplicated.
> 1 votes

---
Tags: hardware, costs
---


title: libgdx draw issue and animation

text:
# Question
Title: libgdx draw issue and animation
it seems as though i cannot get the draw method to work??? it seems as though the bullet.draw(batcher) does not work and i cannot understand why as the bullet is a sprite. i have made a Sprite\[\] and added them as animation. could that be it?

i tried

```
batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY(), bullet.getOriginX() / 2, bullet.getOriginY() / 2, bullet.getWidth(), bullet.getHeight(), 1, 1, bullet.getRotation());

```

but that dont work, the only way it draws is this

```
batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY());

```

below is the code.

// this is in a Asset Class

```
texture = new Texture(Gdx.files.internal("SpriteN1.png"));
texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);

bullet1 = new Sprite(texture, 380, 350, 45, 20);
bullet1.flip(false, true);

bullet2 = new Sprite(texture, 425, 350, 45, 20);
bullet2.flip(false, true);

Sprite[] bullets = { bullet1, bullet2 };
bulletAnimation = new Animation(0.06f, bullets);
bulletAnimation.setPlayMode(Animation.PlayMode.LOOP);

```

// this is the GameRender class

```
public class GameRender() {
private Bullet bullet;
private Ball ball;

public GameRenderer(GameWorld world) {
myWorld = world;
cam = new OrthographicCamera();
cam.setToOrtho(true, 480, 320);

batcher = new SpriteBatch();
// Attach batcher to camera
batcher.setProjectionMatrix(cam.combined);

shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);

// Call helper methods to initialize instance variables
initGameObjects();
initAssets();
}

private void initGameObjects() {
ball = GameWorld.getBall();
bullet = myWorld.getBullet();
scroller = myWorld.getScroller();
}

private void initAssets() {
ballAnimation = AssetLoader.ballAnimation;
bulletAnimation = AssetLoader.bulletAnimation;
}

public void render(float runTime) {

Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

batcher.begin();
// Disable transparency
// This is good for performance when drawing images that do not require
// transparency.
batcher.disableBlending();

// The ball needs transparency, so we enable that again.
batcher.enableBlending();

batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(),         ball.getWidth(), ball.getHeight());

batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(),     bullet.getY());

// End SpriteBatch
batcher.end();
}
}

```

// this is the gameworld class

```
public class GameWorld {

public static Ball ball;
private Bullet bullet;
private ScrollHandler scroller;

public GameWorld() {
ball = new Ball(480, 273, 32, 32);
bullet = new Bullet(10, 10);
scroller = new ScrollHandler(0);
}

public void update(float delta) {
ball.update(delta);
bullet.update(delta);
scroller.update(delta);
}

public static Ball getBall() {
return ball;
}

public ScrollHandler getScroller() {
return scroller;
}

public Bullet getBullet() {
return bullet;
}
}

```

is there anyway so make the sprite work?

# Answer
You must initialise the bullet first, then it should work. If not then do this:

```
batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime),
             bullet.getX(),
             bullet.getY(),
             bullet.getOriginX(),
             bullet.getOriginY(),
             bullet.getWidth(),
             bullet.getHeight(),
             1,
             1,
             bullet.getRotation());

```
> 1 votes

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


# Question
Title: libGDX collision detection / bounding the object
I am trying to implement collision detection so I am drawing a red rectangle to see if it is working. When I put the code below into the update method to check if it is going to work the position is not in the right place. The red rectangle starts from the middle and not at the x and y point? So it draws it wrong.

I also have a getter method so nothing wrong there.

```
bullet.set(getX(), getY(), getOriginX(), getOriginY());

```

this is for the render

```
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.RED);
shapeRenderer.rect(bullet.getX(), bullet.getY(), bullet.getOriginX(), bullet.getOriginY(), 15, 5, bullet.getRotation());
shapeRenderer.end();

```

I have tried to do it with a circle but the circle draws in the middle and I want it to be at the tip of the bullet. At the front of the bullet. x, y point.

```
boundingCircle.set(getX() + getOriginX(), getY() + getOriginY(), 4.0f);

shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.RED);
shapeRenderer.circle(bullet.getBoundingCircle().x, bullet.getBoundingCircle().y, bullet.getBoundingCircle().radius);
shapeRenderer.end();

```

I need it to be of the x and y as the bullet is in the middle of the sprite when drawn originally via paint.

# Answer
> 1 votes
To change the origin of your bounds, you can add the width/height of the rectangle, or subtract.

If the origin of the rectangle is bottom left but you need it positioned from the centre, you would do:

```
rect.x + (width / 2), rect.y + (height / 2)

```

This will take the x coordinate, add the half width on which puts the x value at a midpoint along the rect.

Play around with this to fit your code.

---
Tags: java, android, collision-detection, libgdx
---


# Question
Title: LibGDX onTouch() method Array and flip method
How can I add this on my application. i want to use the onTouch() method from the implementation of the InputProcessor to kill the enemies on screen. how do i do that? do i have to do anything to the enemy class? also i am trying to add a Array of enemies and it keeps throwing exceptions or the bullet now is facing LEFT \<--- again after I used the flip method in the bullet class.

All the code is below so please anyone feel free to have a look thanks. please help Thank you

M

// This is the bullet class.

```
public class Bullet extends Sprite {

public static final float BULLET_HOMING = 6000;
public static final float BULLET_SPEED = 300;
private Vector2 velocity;
private float lifetime;
private Rectangle bul;

public Bullet(float x, float y) {
 velocity = new Vector2(0, 0);
 setPosition(x, y);
AssetLoader.bullet1.flip(true, false);
AssetLoader.bullet2.flip(true, false);
setSize(AssetLoader.bullet1.getWidth(), AssetLoader.bullet1.getHeight());
bul = new Rectangle();
}

public void update(float delta) {
 float targetX = GameWorld.getBall().getX();
 float targetY = GameWorld.getBall().getY();
 float dx = targetX - getX();
 float dy = targetY - getY();

 float distToTarget = (float) Math.sqrt(dx * dx + dy * dy);
 dx /= distToTarget;
 dy /= distToTarget;
 dx *= BULLET_HOMING;
 dy *= BULLET_HOMING;
 velocity.x += dx * delta;
 velocity.y += dy * delta;

 float vMag = (float) Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
 velocity.x /= vMag;
 velocity.y /= vMag;
 velocity.x *= BULLET_SPEED;
 velocity.y *= BULLET_SPEED;

 bul.set(getX(), getY(), getOriginX(), getOriginY());

 Vector2 v = velocity.cpy().scl(delta);
 setPosition(getX() + v.x, getY() + v.y);
 setOriginCenter();
 setRotation(velocity.angle());
 }

public Rectangle getBounds() {
    return bul;
}
public Rectangle getBounds1() {
    return this.getBoundingRectangle();
}
}

```

// This is the class where i load all the images from

```
 public class AssetLoader {
 public static Texture texture;
 public static TextureRegion bg, ball1, ball2;
 public static Animation bulletAnimation, ballAnimation;
 public static Sprite bullet1, bullet2;

 public static void load() {

 texture = new Texture(Gdx.files.internal("SpriteN1.png"));
 texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);

 bg = new TextureRegion(texture, 80, 421, 395, 30);
 bg.flip(false, true);

 ball1 = new TextureRegion(texture, 0, 321, 32, 32);
 ball1.flip(false, true);

 ball2 = new TextureRegion(texture, 32, 321, 32, 32);
 ball2.flip(false, true);

 bullet1 = new Sprite(texture, 380, 350, 45, 20);
 bullet1.flip(false, true);

 bullet2 = new Sprite(texture, 425, 350, 45, 20);
 bullet2.flip(false, true);

 TextureRegion[] balls = { ball1, ball2 };
 ballAnimation = new Animation(0.16f, balls);
 ballAnimation.setPlayMode(Animation.PlayMode.LOOP);
 }

 Sprite[] bullets = { bullet1, bullet2 };
 bulletAnimation = new Animation(0.06f, aims);
 bulletAnimation.setPlayMode(Animation.PlayMode.LOOP);
 }

 public static void dispose() {
 texture.dispose();
 }

```

// This is for the rendering or drawing onto the screen/canvas.

```
 public class GameRenderer {
 private Bullet bullet;
 private Ball ball;

 public GameRenderer(GameWorld world) {
 myWorld = world;
 cam = new OrthographicCamera();
 cam.setToOrtho(true, 480, 320);

 batcher = new SpriteBatch();
 // Attach batcher to camera
 batcher.setProjectionMatrix(cam.combined);

 shapeRenderer = new ShapeRenderer();
 shapeRenderer.setProjectionMatrix(cam.combined);

 // Call helper methods to initialize instance variables
 initGameObjects();
 initAssets();
 }

 private void initGameObjects() {
 ball = GameWorld.getBall();
 bullet = myWorld.getBullet();
 scroller = myWorld.getScroller();
 }

 private void initAssets() {
 ballAnimation = AssetLoader.ballAnimation;
 bulletAnimation = AssetLoader.bulletAnimation;
 }

 public void render(float runTime) {

 Gdx.gl.glClearColor(0, 0, 0, 1);
 Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

 batcher.begin();

 batcher.disableBlending();

 batcher.enableBlending();

 batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight());

        batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY(), bullet.getOriginX(), bullet.getOriginY(), bullet.getWidth(), bullet.getHeight(), 1.0f, 1.0f, bullet.getRotation());

 // End SpriteBatch
 batcher.end();
 }
 }

```

// this is to load the image etc on the screen i guess

```
 public class GameWorld {

 public static Ball ball;
 private Bullet bullet;
 private ScrollHandler scroller;

 public GameWorld() {
 ball = new Ball(480, 273, 32, 32);
 bullet = new Bullet(10, 10);
 scroller = new ScrollHandler(0);
 }

 public void update(float delta) {
 ball.update(delta);
 bullet.update(delta);
 scroller.update(delta);
 }

 public static Ball getBall() {
 return ball;
 }

 public ScrollHandler getScroller() {
 return scroller;
 }

 public Bullet getBullet() {
 return bullet;
 }
 }

```

//This is the input handler class

```
public class InputHandler implements InputProcessor {

private Ball myBall;
private Bullet bullet;
private GameRenderer aims;

// Ask for a reference to the Soldier when InputHandler is created.
public InputHandler(Ball ball) {

    myBall = ball;

}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {

 return false;
}

@Override
public boolean keyDown(int keycode) {
    return false;
}

@Override
public boolean keyUp(int keycode) {
    return false;
}

@Override
public boolean keyTyped(char character) {
    return false;
}

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

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    return false;
}

@Override
public boolean mouseMoved(int screenX, int screenY) {
    return false;
}

@Override
public boolean scrolled(int amount) {
    return false;
}
}

```

i am rendering all graphics in a GameRender class and a gameworld class if you need more info please let me know

I am trying to make the array work but keep finding that when an array is initialized then the bullet fips back to the original and ends up being backwards???? and if I create an array I keep getting Exceptions throw??? Thank you for any help given.

# Answer
I really don't see the issue with creating a new object for this sort of thing. If it's just a static thing though, you can just make an array of objects, and reset them. Something sort of like:

```
Bullet bulletArray[] = new Bullet[5];
for(int i = 0; i < 5; i++){
 bulletArray[i] = new Bullet(x,y,width,height);
}

```

on initializing, then on update something like this:

```
for(int i = 0; i < 5; i++){
 if(bulletArray[i].x > 0 - bulletArray[i].width){
     bulletArray[i].x -= BULLET_SPEED;
}else{
    bulletArray[i].x = screenWidth;
}
}

```

with a spear class that looks like this:

```
public class Bullet{
int x, y, width, height;
Bullet(int xx, int yy, int w, int h){
x = xx;
y = yy;
width = w;
height = h;
}
}

```

You'll have to handle rendering and collision yourself.
> 1 votes

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


# Question
Title: Is an extra collision-mesh for level-data worth the hassle?
What is the optimal approach for collision-detection with the environment in an 3D engine (with triangle mesh based geometry, no bsp)?

**A)** Use the render mesh

* **\[+\]** no need for additional work for artists to fiddle with collision detection
* **\[-\]** high detail is harder for physics calculation
* **\[+/-\]** maybe use collidable flags for materials
* **\[+/-\]** compute the collision-mesh from the render-mesh

**B)** Use an additional collision mesh

* **\[+\]** faster/more optimal collision-detection
* **\[-\]** additional work (either by the artist or by the programmer who has to develop an algorithm to compute it from the render-mesh)
* **\[-\]** more memory useage

How do AAA title handle this? And what are the indie dev's approaches?

# Answer
You do not want to use the render meshes exclusively (if at all).

Back in the days of Quake 3, its curved surfaces (quadratic bezier patches) were evaluated at load-time using a "Geometric Detail" user setting for tessellation quality. If collision were done against those surfaces it would have killed CPU performance. So instead brush planes were used, they approximated the curvature of the surface several orders of magnitude simpler for the sake of collision.

Doom 3 did away with this, and evaluated curved surfaces at level build-time... there were several reasons for this, but it meant that collision geometry was once again relatively static. Modern games are back to the point where patch-based surfaces are evaluated using varying degrees of quality at render-time (DX11/GL4 tessellation). You cannot possibly hope to match your collision geometry against what is being rendered on screen when it is dynamically tessellated (you also would not gain much by implementing such fine-grained collision), so that actually necessitates separate simplified collision geometry.

In fact, gameplay often relies on collision against things that are never actually rendered. There are collision meshes to keep AI from taking certain undesirable paths, to prevent players from running off into the distance, and so on. You will probably never get away with simply colliding against the rendered geometry in a reasonably sophisticated game.
> 2 votes

# Answer
I would leave this decision to the artist:

* Option to enable collision flag for low poly models
* Option to also enable invisible flag for additional collision mesh

I worked with Cryengine and there it was also handled similar, but the "collision" material´s invisibility was not a option.
> 0 votes

---
Tags: collision-detection, 3d
---


title: Is Unity's Random seeded automatically?

text:
# Question
Title: Is Unity's Random seeded automatically?
I seem to recall Unity's Random is automatically seeded; checking the documentation it doesn't say it outright, but a certain interpretation of their words might seem to imply it.

> The seed **is normally set** from some arbitrary value like the system clock before the random number functions are used. This prevents the same run of values from occurring each time a game is played and thus avoids predictable gameplay. However, it is **sometimes** useful to produce the same run of pseudo-random values on demand by **setting the seed yourself**.

*(emphasis added)*

# Answer
> 6 votes
While the text you've quoted may be interpreted in different ways, I'd consider the actual (Javascript) code example to be pretty obvious:

```
// If you comment out the following line, the sequence of random
// values will be different each time you run. However, the sequence
// will always be the same for any particular seed value.
Random.seed = 42;

```

This clearly states that you're able to not set any seed on your own and you'd still end up with "real" random numbers (i.e. the initial seed isn't an arbitrary number).

I don't think they'd make such a basic mistakes as providing platform dependent behavior (like forcing you to set a seed on a platform).

As such, I'd consider the wording *normally set* to refer to using some dynamic number (like time) rather than an arbitrary number. It's not about whether (or how) the seed is initialized by default.

# Answer
> 4 votes
I couldn't find any very reliable source but it seems that everybody agrees that the seed are automatically set to the current time when you create your random instance.

Someone here, here and here says that you should use random.seed only if you want repeatable sequences.

# Answer
> 4 votes
I made some tests. If you seed the random explicitly:

```
Random.seed = 50;
float r1 = Random.value;               // Same random sequence on each run
float r2 = Random.Range(0.0f, 100.0f); // Same random sequence on each run
int   r3 = Random.Range(0, 100);       // Same random sequence on each run

```

If you don't seed it, then its totally random:

```
// Random.seed = 50; // Don't seed
float r1 = Random.value;               // Different random sequence on each run
float r2 = Random.Range(0.0f, 100.0f); // Different random sequence on each run
int   r3 = Random.Range(0, 100);       // Different random sequence on each run

```

---
Tags: unity, random
---


# Question
Title: Why are payments for a game sometimes called "donations"?
Why are money payments (by SMS, or VISA) sometimes called "donations", and not "payments" or "purchases"? Is it a legal part of monetization (some details will be appreciated in this case), or just a habit (who was the first)?

# Answer
> 2 votes
So far I've encountered the term "Donation" for "Cash shop payment" only among amateurs who host smaller games in their free-time (often half-legal private servers which emulate the server software of commercial MMORPGs). Anyone who is an actual professional uses the term "payment" and is proud of it.

Many amateur MMORPGs want to keep up the image of a non-profit volunteer initiative without commercial interest. They hope that by not giving the appearance of a profit-oriented business, they can stay under the radar of both the IRS (to avoid bookkeeping duties) and also IP holders, because often the software and assets they use might not be *quite* legal to use for them.

This strategy is usually flawed. Some server operators make much more money through "donations" than is required to cover their fix-cost and generate an income for them. And even when they wouldn't - it would likely not protect them from any legal issues whatsoever.

Another context where the term "Donation" sometimes pops up is during crowdfunding. While supporting a crowdfunded project often feels like a donation you pay because you really want to see the project to become reality, it actually isn't. A true donation is when your expect nothing in return. But very few crowdfunding initiatives do not reward their backers in some way. Backers usually receive a copy of the finished game, merchandise or other rewards for their money. So when people contribute money to a crowdfunding, it is basically a very early preorder of the planned product.

---
Tags: legal, monetization, terminology
---


# Question
Title: libgdx arrays onTouch() method and delays for objects
I am trying to create random bullets but it is not working for some reason. also how can I make a delay so the bullets come every 30 seconds or 1 minute? Also the onTouch method does not work and it is not taking the bullet away?

Shall I put the array in the GameRender class?

**bullet class**

```
public class Bullet extends Sprite {

public static final float BULLET_HOMING = 6000;
public static final float BULLET_SPEED = 300;
private Vector2 velocity;
private float lifetime;
private Rectangle bul;

public Bullet(float x, float y) {
 velocity = new Vector2(0, 0);
     setPosition(x, y);
AssetLoader.bullet1.flip(true, false);
AssetLoader.bullet2.flip(true, false);
setSize(AssetLoader.bullet1.getWidth(), AssetLoader.bullet1.getHeight());
bul = new Rectangle();
}

public void update(float delta) {
 float targetX = GameWorld.getBall().getX();
 float targetY = GameWorld.getBall().getY();
 float dx = targetX - getX();
 float dy = targetY - getY();

 float distToTarget = (float) Math.sqrt(dx * dx + dy * dy);
 dx /= distToTarget;
     dy /= distToTarget;
 dx *= BULLET_HOMING;
 dy *= BULLET_HOMING;
 velocity.x += dx * delta;
 velocity.y += dy * delta;

 float vMag = (float) Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
 velocity.x /= vMag;
 velocity.y /= vMag;
 velocity.x *= BULLET_SPEED;
 velocity.y *= BULLET_SPEED;

 bul.set(getX(), getY(), getOriginX(), getOriginY());

 Vector2 v = velocity.cpy().scl(delta);
 setPosition(getX() + v.x, getY() + v.y);
 setOriginCenter();
 setRotation(velocity.angle());
 }

public Rectangle getBounds() {
return bul;
}
public Rectangle getBounds1() {
return this.getBoundingRectangle();
}
}

```

**game world class**

```
public class GameWorld {

public static Ball ball;
private Bullet bullet1;
    private ScrollHandler scroller;
    private Array<Bullet> bullets = new Array<Bullet>();

    public GameWorld() {
    ball = new Ball(280, 273, 32, 32);
    bullet = new Bullet(-300, 200);
    scroller = new ScrollHandler(0);
    bullets.add(new Bullet(bullet.getX(), bullet.getY()));

    bullets = new Array<Bullet>();

    Bullet bullet = null;
    float bulletX = 0.0f;
    float bulletY = 0.0f;
    for (int i=0; i < 10; i++) {
       bulletX = MathUtils.random(-10, 10);
       bulletY = MathUtils.random(-10, 10);
       bullet = new Bullet(bulletX, bulletY);

       bullets.add(bullet);
    }
}

public void update(float delta) {
    ball.update(delta);
    bullet.update(delta);
    scroller.update(delta);
}

public static Ball getBall() {
    return ball;
}

public ScrollHandler getScroller() {
    return scroller;
}

public Bullet getBullet1() {
    return bullet1;
}
}

```

This is my **game render class**

```
public class GameRenderer {
private Bullet bullet;
 Ball ball;

 public GameRenderer(GameWorld world) {
 myWorld = world;
 cam = new OrthographicCamera();
 cam.setToOrtho(true, 480, 320);

 batcher = new SpriteBatch();
 // Attach batcher to camera
 batcher.setProjectionMatrix(cam.combined);

 shapeRenderer = new ShapeRenderer();
 shapeRenderer.setProjectionMatrix(cam.combined);

 // Call helper methods to initialize instance variables
 initGameObjects();
 initAssets();
 }

 private void initGameObjects() {
 ball = GameWorld.getBall();
 bullet = myWorld.getBullet();
 scroller = myWorld.getScroller();
 }

 private void initAssets() {
 ballAnimation = AssetLoader.ballAnimation;
 bulletAnimation = AssetLoader.bulletAnimation;
 }

 public void render(float runTime) {

 Gdx.gl.glClearColor(0, 0, 0, 1);
 Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

 batcher.begin();

 batcher.disableBlending();

 batcher.enableBlending();

 batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(),     ball.getY(), ball.getWidth(), ball.getHeight());

    batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY(), bullet.getOriginX(), bullet.getOriginY(), bullet.getWidth(), bullet.getHeight(), 1.0f, 1.0f, bullet.getRotation());

 // End SpriteBatch
batcher.end();
 }
 }

```

I also tried this and it is not working, I used this in the GameRender class

```
Array<Bullet> enemies=new Array<Bullet>();

//in the constructor of the class
enemies.add(new Bullet(bullet.getX(), bullet.getY()));

 // this throws an exception for some reason??? this is in the render method
for(int i=0; i<bullet.size; i++)
   bullet.get(i).draw(batcher);

//this I am using in any method that will allow me from the constructor to update to render
for(int i=0; i<bullet.size; i++)
bullet.get(i).update(delta);

```

this is not taking the bullet out

```
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
for(int i=0; i<bullet.size; i++)
 if(bullet.get(i).getBounds().contains(screenX,screenY))
     bullet.removeIndex(i--);
return false;
}

```

Thanks for the help anyone.

# Answer
Please try the following, went through it again and I think this is the issue:

```
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
   for(int i=0; i<bullet.size; i++)
   {
      if(bullet.get(i).getBounds().contains(screenX,screenY))
         bullet.removeIndex(i);
         //with bullet.removeIndex(i--) - you are removing the previous index
         //from the array indifferent if it's bounding box touched the screen position from onTouch.
   }
   return false;
}

```
> 1 votes

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


# Question
Title: What's the best way to handle numerous recurring log entries in game loop?
I have a custom logging system, use of which is scattered all over the engine and game. The system is linked to a "LogStore" that has an `std::vector<string> logs[NUM_LOG_TYPES]` \- each vector corresponds with it's log type (info, error, debug, etc.). There's one extra std::vector that has "coordinates" to all log entries in the order they were received.

Now, all the logging output is also displayed inside my development console in the game. The game console is handled by HTML-type GUI and therefore requires a new `<p>` element being added for each log output.

My problem is that the log entries that are generated in the main loop each frame freeze the engine, because they continue to add elements to the in-game console, and if the console or guy generates a warning - that creates an infinite logging loop.

I want to solve it by handling the recurring log entries in an elegant way that lets you know that something is critically wrong, but won't freeze the engine - like displaying the count of errors in the last 60 frames instead of displaying errors themselves. But how do you guys handle this? Does anyone know any nifty tricks to do this?

I understand the question may sound vague, but if someone came across this type of issue I'm sure they would know exactly what's happening.

Example problematic log entries:

* OpenGL warnings (I actually do check for errors every frame in many places)
* Really any prints anywhere in the main loop (may be debugging, may be warnings)

# Answer
> 1 votes
There are some basic techniques you can use to reduce log spam.

You can implement a runtime-configurable log verbosity filter. This allows you to reject the display of log messages below are certain filter level (for example, allowing you to display only errors, hiding debug and warning classes of message). You can obviously make this filter apply both (and/or independently) to the visual display of the log messages during the game and the saved logs on the disk. Since you are already tracking the verbosity level of each message, this should be relatively simple.

You can implement message throttling. This involves defining, where the message is logged, a value indicating how often the log message appears. For example,

```
Log(LogInterval.AtMostOncePerSecond, "I am a log message!")

```

Here, `LogInterval.AtMostOncePerSecond` is either an enumerated constant, a symbol representation of a floating point time span, or a number of game frames. Whatever works for you to define how often the log message should pop up on the screen. This generally involves storing more than just the final `std::string` in the log buffer, though; you'll want to make some kind of `LogEntry` structure to contain the relevant data, such as the interval, the last time the message *was* processed to the screen, and some unique identifier for the message (more on that later).

You can also implement duplicate detection and compression. This means that if you see a consecutive collection of log messages, all with the same unique identifier, you only display the first one and a repeat count (`"I am a log message! (x15 times)"`). This, like above, generally works best if you store more than just a string in the log message storage. Like above, it will also warrant the use of some unique identifier (although not necessarily the same identifier as above, if you also do throttling).

---

Uniquely identifying log messages has a bit of a subjective art to it. There are several ways you can implement it, with potential pros and cons. You should choose the one that works best for you.

You could consider the message text the unique property. I think this is the worst option, personally, because it means two textually identical messages in two different source locations could be throttled or suppressed, making it more difficult to figure out which code is the offending code. It also means slight variations in message state (`"Bad render state value: 22 for field AlphaMask."` and `"Bad render state value: -10 for field DepthMask."`) will *not* clump together for throttling and duplicate detection purposes, and usually this isn't what I want.

Alternatively, you can consider the source location (via `__FILE__` and `__LINE__` in C++ or similar constructs in other languages) the unique thing. This tends to flip the behavior from the first option around on its head.

You can also consider messages unique based on the *format string* instead of the unformatted value (in the case of the fake render state message above, that would be `"Bad render state value: {0} for field {1}."`).

I personally tend to use different methods for throttling and for duplicate detection (and usually do both), but the specific methods I choose tends to depend on what the general shape of the logging in an individual project tends to be.

---
Tags: c++, debugging
---


# Question
Title: XNA 4: RenderTarget2D textures getting transparent on fullscreen
I'm generating a `Texture2D` object using `RenderTarget2D` as in the following code

```
public static Texture2D GetTextTexture(string text, Vector2 position, SpriteFont font, Color foreColor, Color backColor, Texture2D background=null)
{
            int width = (int)font.MeasureString(text).X;
            int height = (int)font.MeasureString(text).Y;

            GraphicsDevice device = Settings.game.GraphicsDevice;
            SpriteBatch spriteBatch = Settings.game.spriteBatch;

            RenderTarget2D renderTarget = new RenderTarget2D(device, width,
            height, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8,
            device.PresentationParameters.MultiSampleCount, RenderTargetUsage.DiscardContents);

            device.SetRenderTarget(renderTarget);
                device.Clear(backColor);
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
                if (background != null) spriteBatch.Draw(background, new Rectangle(0, 0, 70, 70), Color.White);
                spriteBatch.End();
                spriteBatch.Begin();
                spriteBatch.DrawString(font, text, position, foreColor, 0, new Vector2(0), 0.8f, SpriteEffects.None, 0);
                spriteBatch.End();
            device.SetRenderTarget(null);
            ResetGraphicsDeviceSettings();
            return (Texture2D)renderTarget;
}

```

It's working all fine. But when I `ToggleFullScreen()` (and vice-versa), the previous textures are getting transparent. However, the new textures after that are being generated correctly.

What can be the reason for this?

# Answer
> 1 votes
`ToggleFullScreen()` causes the `GraphicsDevice` to be reset and when the `GraphicsDevice` is reset the default behavior of the `RenderTarget2D` is to loose its data.

You have 2 options.

1. You can copy the color data into a Texture2D.

```
Color[] texdata = new Color[Width * Height];
renderTarget.GetData(texdata);
texture.SetData(texdata); //<-- you would want to return this texture

```
2. You can hook into the Content Lost Event and rebuild the `RenderTarget2D` when needed.

Personally I recommend #1, especially it its a one time operation such as at level loading, since it helps keep things simple since you're back to only dealing with standard Texture2Ds and everything is back on CPU side memory.

---
Tags: c#, textures, xna-4.0, rendertargets
---


title: Converting DDS textures to TGA

text:
# Question
Title: Converting DDS textures to TGA
I have a model which has textures in DDS format, but my game takes textures in TGA format. How can I convert the textures from DDS to TGA?

# Answer
> 3 votes
You can convert .dds to .tga with a variety of tools, such as

# Answer
> 2 votes
In addition to the tools NathanReed mentioned, ImageMagick can now also do this.

It supports more source (and target) formats than the NVidia texture tools, which is quite convenient, and allows performing lots of image operations during conversion (like flipping, scaling to powers of two etc). http://www.imagemagick.org

Example:

```
convert -flip foo.png foo.dds

```

---
Tags: textures, dds
---


title: OpenGL flickerinng near the edges

text:
# Question
Title: OpenGL flickerinng near the edges
I am trying to simulate particles moving around the scene with OpenCL for computation and OpenGL for rendering with GLUT. There is no OpenCL-OpenGL interop yet, so the drawing is done in the older fixed pipeline way. Whenever circles get close to the edges, they start to flicker. The drawing should draw a part of the circle on the top of the scene and a part on the bottom.

The effect is the following:

The balls you see on the bottom should be one part on the bottom and one part on the top. Wrapping around the scene, so to say, but they constantly flicker.

The code for drawing them is:

```
void
Scene::drawCircle(GLuint index){
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glTranslatef(pos.at(2*index),pos.at(2*index+1),  0.0f);

    glBegin(GL_TRIANGLE_FAN);
    GLfloat incr = (2.0 * M_PI) / (GLfloat) slices;
    glColor3f(0.8f, 0.255f, 0.26f);
    glVertex2f(0.0f, 0.0f);
    glColor3f(1.0f, 0.0f, 0.0f);
    for(GLint i = 0; i <=slices; ++i){
        GLfloat x = radius * sin((GLfloat) i * incr);
        GLfloat y = radius * cos((GLfloat) i * incr);

        glVertex2f(x, y);
    }
    glEnd();
}

```

If it helps, this is the reshape method:

```
 void
 Scene::reshape(GLint width, GLint height){
     if(0 == height) height = 1; //Prevent division by zero

     glViewport(0, 0, width, height);

     glMatrixMode(GL_PROJECTION);
     glLoadIdentity();

     gluOrtho2D(xmin, xmax, ymin, ymax);
     std::cout << xmin << " " << xmax << " " << ymin << " " << ymax << std::endl;
 }

```

# Answer
Regardless of other glitches you have, in order to draw a shape in a wrapping world, you need to duplicate it on both sides of a wrapping edge if it's intersecting that edge. You should perform bounding shape tests to determine if such an overlap exists.

This means that for a particular shape, you may need to draw it up to four times if it straddles a corner.

There is no base knowledge of wrapping worlds in OpenGL but you may be able to use geometry shaders to synthesize additional geometry.
> 3 votes

# Answer
What makes you think that GL should draw part of your object at the top and part at the bottom if its position spans the edge? What will actually happen is that GL will clip the vertices.

For some primitive types (e.g. points) this by itself will produce flickering since a single infinitely small point is used to clip a primitive that actually has an area (e.g. if the center of the point is offscreen, the entire thing disappears). You are not using point primitives here; this was just a simple example of clipping in action.

The only way to produce the wrapping behavior you want is if you determine which of your objects straddles the edges of the viewport. This can be done generally if you transform them into clip-space (projection **x** view **x** model **x** vertex) and test for objects with coordinates **\> w** or **\< -w**. Any objects with offending coordinates must be drawn twice, the second time you draw them you need to add/subtract `2 * w` from the clip-space X or Y coordinates (you can do this very easily with a vertex shader and a second pass). You probably do not want to wrap objects that are behind your near plane or beyond your far plane, but you ***could*** do that the same way.
> 1 votes

---
Tags: opengl, c++
---


# Question
Title: Without using a pre-built physics engine, how can I implement 3D collision detection from scratch?
I want to tackle some basic 3D collision detection and was wondering how engines handle this and give you a pretty interface and make it so easy... I want to do it all myself, however.

2D collision detection is extremely simple and can be done multiple ways that even beginner programmers could think up:

1. When the pixels touch;
2. when a rectangle range is exceeded;
3. when a pixel object is detected near another one in a pixel-based rendering engine.

But 3D is different with one dimension, but complex in many more so... **what are the general, basic understanding/examples on how 3D collision detection can be implemented?**

Think two shaded, OpenGL cubes that are moved next to each other with a simple OpenGL rendering context and keyboard events.

# Answer
This is one of those "It depends..." answers, be forewarned :)

The complexity of collision detection in 3D depends on the complexity of the bounding volume for solids. By bounding volumes, I mean what shape you are wanting to consider for the collision calculations. You might be drawing a really complicated spikey ball on the screen, but consider that treating it like a sphere might be just fine.

**The Really Easy Way**

Model everything with a sphere. Then you just have to measure the distance between object centers, and if the distance between two objects is \<= the radius of both, you know there's a collision.

You might consider this a poor way to do it, but if you really don't care about "perfect" collisions, then it might be just fine. Do you really need perfect collisions? Can you get by with a bit of fuzziness? Then modelling as spheres is great.

**The More Challenging Way**

Ah if only life were just billiards games... If you can't use spheres, you're going to have to start computing intersections between more complicated solids. Which I'm guessing there are many resources for online. And that I really don't understand it well enough to give a good answer.

You can still use spheres as a quick 'first pass' approach. Give each solid a bounding sphere, and if you have no overlapping spheres, then you know there's no chance of a collision, so it's not worth bothering with more expensive calculations.

**An Incremental Development Approach**

You've expressed interest in doing this yourself, which is great - but also potentially a complicated undertaking. To up your odds of completing it, I'd suggest doing the work in steps

First, start with a "minimum viable collision system" - start with the spheres method. Get your environment working with sphere collisions. Will it be perfect? No. But it will give you a good rough idea of how collision as a game element work.

Next, when you're happy with it (in the sense it works with spheres), then start adding complex collision detection. That actually fits nicely with using collisions as a 'first pass' calculation in a complex environment.
> 4 votes

# Answer
A simple solution is to use bounding-boxes.

Calculate an invisible box around each of your game objects. When two of these boxes intersect, you have a collision.

When you need more accuracy, you can make each object consist of multiple bounding boxes, so they approximate its geometry more closely. This answer on Arquade has screenshots of first person shooters with visible bounding-boxes.
> 1 votes

---
Tags: collision-detection, physics, architecture
---


# Question
Title: How do I add an image inside a rectangle or a circle in JavaFX?
Suppose we have a rectangle called r

```
Rectangle r = new Rectangle(40, 20);

```

and an image called image

```
Image image = new Image("...src for image");

```

How do I fit the image inside the rectangle? Also, how can I make the image move if the rectangle moves too? How do I do the same thing for a circle? Code examples are greatly appreciated.

# Answer
> 3 votes
If you absolutely need to use a Rectangle, you can use an ImagePattern and set it as the fill for the Rectangle. Only do this if you want the Rectangle for the rounded corners, the ability to have a 'border' (stroke, inherited from Shape), or some other feature of Rectangle. Otherwise, I suggest using an ImageView.

I'm actually trying to figure out the functional difference between these strategies myself, which is how I stumbled upon your post.

```
Image image = new Image("myImage");
Rectangle rekt = new Rectangle(40, 40); //haha
//    ☐ rekt
//    ☐ not rekt
//    ☑ tyrannosaurus rekt
ImagePattern imagePattern = new ImagePattern(image);
rekt.setFill(imagePattern);

ImageView imageView = new ImageView(image);

```

# Answer
> 2 votes
Wrap your shape in a `StackPane`, along with a `Pane` (or any containing `Node`) for your `Image`. When you need to drag, move, scale, or otherwise alter your component, act on the `StackPane`, this will carry changes over to its children, which are your shape and `Pane`:

```
StackPane pane = new StackPane();
Rectangle r = new Rectangle(50, 50);
r.setFill(Color.RED);
Pane p = new Pane();
p.setStyle("-fx-background-image: url("http://www.bogotobogo.com/images/java/tutorial/java_images/Duke256.png");
    -fx-background-repeat: no-repeat;
    -fx-background-size: contain;");
pane.getChildren().addAll(r, p);
r.widthProperty().bind(pane.prefWidthProperty());
r.heightProperty().bind(pane.prefHeightProperty());
pane.setPrefSize(100, 100);

```

The style set on the `Pane` is what causes your image to be resized to the smallest dimension of the `Pane`. That is, if the smallest dimension is the width, the image will be sized (aspect ratio preserved) so it is precisely large enough to fill the entire width. See here to learn about how to play around with the `-fx-background-size` attribute.

The bindings ensure your shape will be the same size as the `StackPane` at all times, so long as you operate with the preferred dimensions (`setPrefSize(double, double)`) of the `StackPane`.

Note that for the `-fx-background-image` attribute, you specify the URL to your desired image.

---
Tags: java, 2d, geometry, image
---


# Question
Title: Splitting Pygame functionality between classes or modules?
I am attempting to make my pygame application more modular so that different functionalities are split up into different classes and modules. I am having some trouble getting pygame to allow me to draw or load images in secondary classes when the display has been set and pygame.init() has been done in my main class.

I have typically used C# and XNA to accomplish this sort of behavior, but this time I need to use python.

How do I init Pygame in class1, then create an instance of class2 which loads and converts() images.

I have tried `pygame.init()` in class 2 but then it tells me no display mode has been set, when it has been set in class1. I am under the impression I do not want to create multiple Pygame displays as that gets problematic.

I am probably missing something pythonic and simple but I am not sure what. How do I create a Display class, init Python and then have other modules do my work like loading images, fonts etc.?

Here is the simplest version of what I am doing:

```
class1:
    def __init__(self):
        self.screen = pygame.display.set_mode((600,400))
        self.imageLoader = class2()

class2:
    def __init__(self):
        self.images = ['list of images']

    def load_images():
        self.images = os.listdir('./images/') #get all images in the images directory
        for img in self.images:
            #read all images in the directory and load them into pygame
            new_img = pygame.image.load(os.path.join('images', img)).convert()
            scale_img = pygame.transform.scale(new_img, (pygame.display.Info().current_w, pygame.display.Info().current_h))
            self.images.append(scale_img)

if __name__ == "__main__":
    c1 = class1()
    c1.imageLoader.load_images()

```

Of course when it tries to load an convert the images it tells me Pygame has not been initialized, so I throw in a `pygame.init()` in class2 (I have heard it is safe to init multiple times) and then the error goes to:

> pygame.error: No video mode has been set

# Answer
> 3 votes
This is what you need to do, in the following order:

1. `pygame.init()` \- this needs to happen before any other use of `pygame`
2. `pygame.display.set_mode()` \- this needs to be done before any other use of `pygame.display`
3. Load and scale your images. Note that `pygame.image.load()` doesn't need `pygame.display.set_mode()`, but you're also using `pygame.display.Info()` to scale your images, hence the order.

You may find this cheatsheet useful: http://inventwithpython.com/pygamecheatsheet.png

When you get an error in Python, you also get the exact line of code that caused that error. That should help tremendously in troubleshooting.

---
Tags: python, pygame
---


# Question
Title: LibGDX drawing map using tiles without space
I am making a board game. To draw the map on the board I use different tiles. On some screen the map looks good but on some other screens there is a space between the tiles. How can I do so there won't be any space between the tiles?

I am designing my game with the size 480x800. To fit other screens I stretch it.

My tiles looks like this:

I draw the map using a for loop to draw the tile in different (x,y) position on screen.

Here is what I mean with space between tiles: Screen with 240x400

Screen with 360x600, here there is no spacing between tiles.

I use camera and the screen to draw I don't use stage. I have also tried to use Viewport but I get the same results.

```
  cam = new OrthographicCamera();cam.setToOrtho(true, gameWidth, gameHeight);
  batcher = new SpriteBatch();
  batcher.setProjectionMatrix(cam.combined);
  shapeRenderer = new ShapeRenderer();
  shapeRenderer.setProjectionMatrix(cam.combined);

```

How can I do to solve the problem?

# Answer
> 1 votes
To be clear, that black border around your tiles is what you are talking about when you say thee is a "space" inbetween the tiles, right?

### You have two options if that is the case:

1. Alter your coordinates for the tiles so that they range not from \[**0**,**1**\] (relative to the packed tile) but rather \[**1/2N**, **1-1/2N**\], where N is the size (in texels) of your tile.
2. Pack your tiles with a border, as described here.

---

The crux of the problem is that you need to implement Edge Clamp behavior (where the texture coordinates are clamped to texel centers instead of the extreme ends of textures). Otherwise, texture filtering will pickup texels from adjacent tiles since you are not using the ***center*** of the texel; the sample point is equally distant from the last texel in your tile as it is the first texel in an adjacent tile if you sample on the border.

However, doing that in a packed texture is complicated. The second solution works best for texture atlases used in 3D rendering, the first solution may be adequate for a simple 2D application such as yours.

---
Tags: java, libgdx
---


# Question
Title: Is ID@Xbox restricted to established studios?
I read through the ID@Xbox site but don't totally understand the program. I am a software developer who has made a few Flash games on my own and would like to try to port or recreate one of them for Xbox One.

Is this program only for established game studios?

# Answer
> 3 votes
The program is specifically designed for independent developers of any size, *not* established studios. Established studios have the more traditional Xbox developer program open to them.

I think the page you linked makes it very clear:

> ID@Xbox is shorthand for the Independent Developers Publishing Program for Xbox One, a new program **enabling independent game developers of** **all sizes** to produce and self-publish games digitally on Xbox One.

You can apply to the program right now. You don't need existing hardware. There is no application fee for the program and, if accepted, you get access to two development kits.

Whether or not you *will* be accepted is another matter, and not something we can answer. In the early days of the program, bias will likely be shown to more established developers (in the sense that they already have games that show well to bring to the system), but that does not preclude your acceptance.

---
Tags: xbox
---


# Question
Title: Is a warning about IAP in freemium games on iOS required?
When I launch the successful iOS game "Clash of Clans", right in the beginning I get the following message in an iOS info pop-up:

"Clash of Clans is free to play, but you can speed up your progress with in-app purchases. If desired, purchases can be disabled in the general settings of your device."

What's the reason the developer shows this message right in the beginning? Is there any legal obligation to do so?

# Answer
There is no legal obligation to do so. There is no Apple TOS obligation to do so. And I will disagree with the other answer and say: There is no moral obligation to do so.

The only way to know why they decided to put this message up would be to ask them. But I suspect it is to let people know that they can buy IAPs to speed things up. It's advertising.

On the iOS app store, any game that contains In App Purchases will say so on the screen where the user buys the app...

As far as I'm concerned this is enough notice to the user. The game doesn't force you to buy them. So the way I see it, Apple puts these hints here to say something similar to "batteries not included".
> 1 votes

# Answer
This is simply a bit of advertising and a warning mixed in to one. They're promoting the fact that you can speed up your progress in the game with purchases. Further, they're letting you know that if you don't want to spend any money, even accidentally, you can disable in-app purchases in the general settings of your device.
> 0 votes

# Answer
There's no legal obligation to do so (only a moral one, if you want to look at it that way). Further, Apple does not mandate that your application include such a notice either (at least not at the time of this writing). Clash of Clans is probably just doing this to be respectful of its player base.

If Apple *did* ever change their policy to mandate such a thing, it's likely they'd just force it on you (they can tell if you application has the potential for IAP; they *do* display this information on the App Store when you are purchasing/downloading an application) and display the prompt when you call into one of their APIs. Much like they do with the permission prompts for accessing your contacts, et cetera.
> 0 votes

---
Tags: legal
---


title: Input handling between game loops

text:
# Question
Title: Input handling between game loops
This may be obvious and trivial for you but as I am a newbie in programming I come with a specific question.

I have three loops in my game engine which are input-loop, update-loop and render-loop. Update-loop is set to 10 ticks per second with a fixed timestep, render-loop is capped at around 60 fps and the input-loop runs as fast as possible. I am using one of the Javascript frameworks which provide such things but it doesn't really matter.

Let's say I am rendering a tile map and the view of which elements are rendered depends on camera-like movement variables which are modified during key pressing. This is only about camera/viewport and rendering, no game physics involved here.

And now, how can I handle input events among these loops to keep consistent engine reaction? Am I supposed to read the current variable modified with input and do some needed calculations in a update-loop and share the result so it could be interpolated in a render-loop? Or read the input effect directly inside the render-loop and put needed calculations inside?

I thought interpreting user input inside an update-loop with a low tick rate would be inaccurate and kind of unresponsive while rendering with interpolation in the final view. How it is done properly in games overall?

# Answer
> 1 votes
You should have your Input in your update loop unless input runs at the same interval as your update loop which in the latter case makes no sense.

In your update loop you are working with your input so if it does not run at the same interval you will miss input.

Let's say your input runs 20 times/s and update 10 times/s:

> On input 9 you press a key, then it runs input again (10) which does not register the key press anymore and then it runs update 5.

You usually handle input updates on top of the update loop, then it will run all the update code which is perfectly synchronized with the input. Then it will render to screen and repeat itself. Having a separate input loop just complicates things and imho is weird.

---
Tags: rendering, input
---


# Question
Title: Finding diagonal objects of an object in 3d space
Using Unity3d, I have a array which is having 8 `GameObjects` in grid and one object (which is already known) is in center like this where K is already known object. All objects are equidistant from their adjacent objects (even with the diagonal objects) which means

(distance between 4 & K) == (distance between K & 3) = (distance between 2 & K)

1 2 3
4 K 5
6 7 8

I want to remove 1,3,6,8 from array (the diagonal objects).
How can I check that at runtime?
my problem is the order of objects {1-8} is not known so I need to check each object's position with K to see if it is a diagonal object or not. so what check should I put with the GameObjects (K and others) to verify if this object is in diagonal position
Regards,
Sam

# Answer
```
If (distance between 4 & K) == (distance between K & 3) == (distance between 2 & K)

```

Then it's a **circle**, therefore *there's no diagonal* :) If there was a diagonal the distance between the diagonal would be `sqrt(2)` times bigger than the distance between the adjacent.

Pick one of the objects that is not K, and order the others by distance (ignore K). Exclude the object you picked, 4th, 5th and the final one.

Example: If you picked 1, ordering the others by distance from 1 would result:

```
2, 4
3, 6
5, 7
8

```

You'd remove 1 (the one you picked), 3 and 6 (4th, 5th), 8 (the last).
> 1 votes

# Answer
One solution would be to get the normal vector between the objects and look at its `x` and `z` components. Diagonal objects will have an identical `x` and `z` length (assuming the objects are arranged on the X/Z plane, otherwise you'd have to swap components accordingly).

In code:

```
// MyObjects is an array or list of your corner GameObjects (1-8)
// K is your center GameObject
foreach(GameObject obj in MyObjects){
    Vector3 normal = (obj.transform.position - K.transform.position).normalized;
    // compare against a small float because of floating-point inaccuracies
    if(Mathf.Abs(Mathf.Abs(normal.x) - Mathf.Abs(normal.z)) < 0.001){
        // diagonal object detected!
    }
}

```
> 1 votes

---
Tags: unity, cocos2d, logic, unityscript
---


title: How should I choose quadtree depth?

text:
# Question
Title: How should I choose quadtree depth?
I'm using a quadtree to prune collision detection pairs in a 2d world. How should I choose to what depth said quadtree is calculated?

The world is made mostly of moving objects1, so the cost of dispatching the objects between the quadtree cells matters. What is the relationship between the gain from less collision checking and the loss from more dispatching? How can I strike a balance that performs optimally?

---

1 To be completely explicit, they are autonomous self-replicating cells competing for food sources. This is an attempt to show my pupils predator-prey dynamics and genetic evolution at work.

# Answer
Of course, if resources are scarce and speed critical, said depth should be determined through benchmarking, but here are some maths to help cornering it.

Let us assume that we are dealing with *n* object for which we have to trace collisions, that their repartition in the world is uniform and they are small enough that no matter how fine the grid is, overlap will be negligible. If we use a depth *d* quadtree, we have *4^d* leaf cells, so that's an average of *n/4^d* objects per cell. If the cost of detecting collisions between N objects is *O(N^p)*, the cost of checking all collisions is

```
4^d⋅(n/4^d)^p

```

If we rebuild the quadtree from scratch, the cost of dispatching the objects between the cells is 2⋅n⋅d. So the total cost is

```
c(n,d,p) = 4^(d-dp)⋅n^p + 2⋅n⋅d

```

So finding an appropriate *d* should not be hard. Interestingly enough, it is not too dependent on *p*, for instance for 100 objects and *p* from 2 to 7, here is a plot *c* (for real-valued *b* to make it easier to read)

Here, 3 seems to be a good *d*. So me mostly have to take *n* into account. For *p=2*, the *n* thresholds I found are

```
   n >  │ d
  ──────┼────
  100   │ 3
  400   │ 4
  1400  │ 5
  5500  │ 6
  22000 │ 7
  87000 │ 8
  350000│ 9

```

Again, the numbers are quite crude and the assumptions quite strong. In particular, if you are dealing with non-ponctual objects, you should definitely make sure that size is still small enough with respect to the grid granularity. But it should at least give a order of magnitude.
> 2 votes

# Answer
For your purpose, I agree with @TravisG, that collision detection via a quadtree may be an overkill. In many Agent Based Modelling and Simulation platforms the world is simply a 2D grid and agents sharing the same grid cell are supposed to be in the same location. This approach of collision detection should be sufficient enough to demonstrate concepts like predator-prey dynamics.

You may run the Wolf Sheep Predation model from Netlogo (download link) and check if it is good enough for your goal.
> 1 votes

---
Tags: collision-detection, optimization, quadtree
---


# Question
Title: Chess Artificial intelligence with python and pygame
I created chess game with python and pygame. Now I'm trying to make Artificial intelligence, but what is actually best way to do it? Some tips, tricks, links?
Thanks

# Answer
> 2 votes
First, you need a rating function. A rating-function analyzes the board, rates which player currently appears to have an advantage, and outputs it as a positive (white has an advantage) or negative (black has an advantage) number.

A trivial way to do this is to just count the material advantage using the relative value system (pawn: 1, bishop: 3, knight: 3, rook: 5, queen: 9). But a more advanced function would also take into account how well the pieces are positioned (for example by increasing value when the piece threatens or protects other pieces or reducing value when it is threatened itself without being adequately protected).

A mate-position would have a rating of +∞ or -∞, depending on which player mates.

Then you use this function to calculate the rating of every currently possible AI move followed by every possible player response to that move. Then pick the AI move where the enemy response with the worst rating (from the PoV of the AI) is still rated higher than the worst-rated response of every other AI move.

A cheap way to make the AI stronger is to not just explore one move into the future but several moves. But keep in mind that the computation time will increase exponential. A much more efficient and elegant way, however, is usually to improve your rating function so the AI can make better strategic decisions.

This method is called the minmax algorithm, and it can be applied to any turn-based game without information hiding. The only thing you have to adapt to each game is the rating function. In a game like chess with a large number of possible moves each turn, the performance can be enhanced through alpha-beta pruning (not following obviously bad tree branches).

Another enhancement which is implemented by most chess engines is an opening library. Chess opening theory is a very well-researched area which is much too complex to model with one simple algorithm. There are whole books which just explore the strategical aspects of *one single* chess opening. That's why chess engines do the same thing most chess players do: Learn the most common openings and the usual reactions to them and just play them from memory.

---
Tags: ai, python, pygame
---


title: Simple Java networking game engine

text:
# Question
Title: Simple Java networking game engine
I want to create a simple java networking game and search a networking engine that eases use of sockets etc. I have already read some questions on here and the internet about java networking for games, but many of them were over 10 years old or not really answered.

I have no idea whatsoever about what exactly I need to send in terms of messages, but I figured simple strings or integers will be enough for my purposes.

It's basically a peer to peer game, so I don't need a centralized server structure. Messaging doesn't have to have an extremely low ping, yet of course all players need to have a synchronized view.

What are the possibilities I have here?

# Answer
You will probably want to build something that is based on the Netty IO library. Netty is a very good IO library suitable for high performance / low latency communications of the type you need in games.

You could use Netty directly, but it might also make sense to use a higher level library that has been specifically designed for games. I found this on Github, might be just what you need:

Alternatively, if you are using a Java game engine like jMonkeyEngine then this may already contain the networking features that you need:
> 4 votes

# Answer
I was reviewing this article today:

For another endeavour (not a game). Fast messaging libraries offer another alternative, especially those for high volume small messages (e.g. twitter, ForEx, Airlines, etc).
> 1 votes

---
Tags: java, networking
---


# Question
Title: Libgdx change color of Texture at runtime
I've also asked this question on StackOverflow.

In a Libgdx game, I have some `Animation`s for my `Player`. All the `Frame`s for this `Animation` are inside a `TextureAtlas`. The `Player` `Texture`s show a human, with a white T-Shirt. The T-Shirt is the only white part of the `Player`.
Now i want to be able to replace the white color with red for `Player`1, with green for `Player`2 and so on. How can I do that, without losing the advantage of the `TextureAtlas` (`Texture` switching)?

Of course 1 way would be to store 4 versions of every `Frame`, for 4 different `Players` (colors). However, there are games out there where you can fully customize the `Player`, give them a blue hat, red pants, and pink shirts and so on. How can this be done?

# Answer
Just use a white texture for the t-shirt. When you draw, change the color of the batch to the color you want for t-shirt. After you draw, change the color of the batch to the original.

I assume you have separate parts for your player and not one texture for the entire player. Parts meaning head, arms, legs, neck, body..etc. That's how other games you mentioned should do it.
> 3 votes

---
Tags: 2d, textures, libgdx
---


# Question
Title: Make objects slide across the screen in random positions
I want to make an object appear randomly at the right hand side of the screen and then slide across the screen and disapear at the left hand side. I am working with libgdx. I have this bit of code but it makes items fall from the top down. Please help.

```
public EntityManager(int amount, OrthoCamera camera) {
    player = new Player(new Vector2(15, 230), new Vector2(0, 0), this, camera);
    for (int i = 0; i < amount; i++) {
        float x = MathUtils.random(0, MainGame.HEIGHT - TextureManager.ENEMY.getHeight());
        float y = MathUtils.random(MainGame.WIDTH, MainGame.WIDTH * 10);
        float speed = MathUtils.random(2, 10);
        addEntity(new Enemy(new Vector2(x, y), new Vector2(-0, -speed)));
    }

```

# Answer
The answer is in your last line:

`addEntity(..., new Vector2(-0, -speed)));`

Speed is set on the Y-axis, which is vertically; you want to replace it with:

`addEntity(..., new Vector2(-speed, 0)));`

Incidentally, your code flips the "normally" understood X and Y coordinates; you're using `x` to indicate vertical position, and `y` to indicate horizontal position.

Also, my two cents: setting a random speed from 1x to 10x with screen width is too much. I would use a smaller range, like 1x-5x (for the line `float y = ...`).
> 1 votes

# Answer
X is horizontal, Y is vertical. You always give these "coordinates" in this order (First X, then Y). This should fix it:

```
addEntity(new Enemy(new Vector2(x, y), new Vector2(-speed, 0)));

```

With this in mind you need to change spawning position as well (I made some comments):

```
public EntityManager(int amount, OrthoCamera camera) {
    player = new Player(new Vector2(15, 230), new Vector2(0, 0), this, camera);
    for (int i = 0; i < amount; i++) {
        float x = MathUtils.random(0, MainGame.HEIGHT - TextureManager.ENEMY.getHeight()); //This should be float y, vertical height
        float y = MathUtils.random(MainGame.WIDTH, MainGame.WIDTH * 10); //This should be float x, horizontal width.
        float speed = MathUtils.random(2, 10);

addEntity(new Enemy(new Vector2(x, y), new Vector2(-0, -speed)));
}

```
> 0 votes

---
Tags: java, android, libgdx, sprites, random
---


# Question
Title: How to pass depth buffer from OGRE to CUDA?
I am using OGRE for rendering some objects. At every frame, I would like to pass the resulting depth buffer to CUDA for running some kernels on it and computing a result.

How can I achieve this? How do I get access to depth buffer in OGRE? How do I pass this to CUDA for processing? I do not need to write to the depth buffer in the CUDA kernels, it can be read-only.

# Answer
> 1 votes
Firstly to get CUDA working you will need to download the correct drivers from NVIDIA for your graphics card.

You will also need to download the CUDA SDK and link against it and #include it in your program.

you can send data to the GPU by allocating a buffer and copying it to the GPU as so:

```
char *buffer;
cudaMalloc( (void**)&buffer, yourBufferSize );
cudaMemcpy( buffer, yourDepthBuffer, csize, cudaMemcpyHostToDevice );

```

To execute a kernel on this data

```
dim3 dimBlock( 1, 1 );
dim3 dimGrid( 1, 1 );
testKernel<<<dimGrid, dimBlock>>>(buffer);
//You'll probably want to decide on your own block size etc ...

```

Where the test Kernel is

```
__global__
void testKernel(char *a)
{
    a[threadIdx.x] = .....; //whatever you want to do
}

```

To get the result back you use

```
cudaMemcpy( yourResult, buffer, yourBufferSize, cudaMemcpyDeviceToHost );

```

And of course clean up after yourself

```
cudaFree( buffer);

```

That's the overall gist of it anyway. You'll probably need to fill is some gaps like error handling and so forth, but I figured it best to keep it simple.

See here for a walkthrough of the basics.

---
Tags: opengl, ogre, depth-buffer, cuda
---


# Question
Title: Render on other render targets starting from one already rendered on
I have to perform a double pass convolution on a texture that is actually the color attachment of another render target, and store it in the color attachment of ANOTHER render target. This must be done multiple time, but using the same texture as starting point

What I do now is (a bit abstracted, but what I have abstract is guaranteed to work singularly)

```
renderOnRT(firstTarget); // This is working.

for each other RT currRT{
    glBindFramebuffer(GL_FRAMEBUFFER, currRT.frameBufferID);
    programX.use();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, firstTarget.colorAttachmentID);
    programX.setUniform1i("colourTexture",0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, firstTarget.depthAttachmentID);
    programX.setUniform1i("depthTexture",1);
    glBindBuffer(GL_ARRAY_BUFFER, quadBuffID); // quadBuffID is a VBO for a screen aligned quad. It is fine.
    programX.vertexAttribPointer(POSITION_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glDrawArrays(GL_QUADS,0,4);

    programY.use();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, currRT.colorAttachmentID); // The second pass is done on the previous pass
    programY.setUniform1i("colourTexture",0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, currRT.depthAttachmentID);
    programY.setUniform1i("depthTexture",1);
    glBindBuffer(GL_ARRAY_BUFFER, quadBuffID);
    programY.vertexAttribPointer(POSITION_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glDrawArrays(GL_QUADS, 0, 4);
}

```

The problem is that I end up with black textures and not the wanted result.

The GLSL programs program(X,Y) works fine, already tested on single targets.

Is there something stupid I am missing?

Even an hint is much appreciated, thanks!

# Answer
> 1 votes
Later edit:

There is a feedback loop in the way you are rendering, read the code again more carefully.

You are drawing to `currRT`, the first convolution step fills in `currRT.colorTexture`. Then in the second draw call you use `currRT.colorTexture` for the second step of the convolution. This produces undefined behavior in GL.

You should use two frame buffers, one that does the first step of the convolution and another that does the second step.

---
Tags: opengl, rendering, rendertargets
---


title: Component-wise GLSL vector branching

text:
# Question
Title: Component-wise GLSL vector branching
I'm aware that it usually is a BAD idea to operate separately on GLSL vec's components separately. For example:

```
//use instrinsic functions, they do the calculation on 4 components at a time.
float dot = v1.x*v2.x + v1.y * v2.y + v1.z * v2.z; //WRONG
float dot = dot(v1, v2); //RIGHT

//Multiply one by one is bad too, since the ALU can do the 4 components at a time.
vec3 mul = vec3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z); //WRONG
vec3 mul = v1 * v2; //RIGHT

```

I've been struggling thinking, **are there equivalent operations for branching?**

For example:

```
vec4 Overlay(vec4 v1, vec4 v2, vec4 opacity)
{
    bvec4 less = lessThan(v1, vec4(0.5));
    vec4 blend;
    for(int i = 0; i < 4; ++i)
    {
        if(less[i]) {
            blend[i] = 2.0 * v1[i] * v2[i];
        } else {
            blend[i] = 1.0 - 2.0 * (1.0 - v1[i]) * (1.0 - v2[i]);
        }
    }
    return v1 + (blend - v1) * opacity;
}

```

This is a Overlay operator that works component wise. I'm not sure if this is the best way to do it, since I'm afraid these `for` and `if` can be a bottleneck later.

Tl;dr, Can I branch component wise? If yes, how can I optimize that Overlay function with it?

# Answer
You can optimize this to be branchless actually, however for seeing if it's faster you always want to profile it:

```
vec4 Overlay(vec4 v1, vec4 v2, vec4 opacity)
{
    bvec4 less = lessThan(v1, vec4(0.5));
    vec4 blendHigh = vec4(1.0) - vec4(2.0) * (vec4(1.0) - v1) * (vec4(1.0) - v2);
    vec4 blendLow = vec4(2.0) * v1 * v2;
    vec4 blend = mix(blendHigh, blendLow, less);

    return v1 + (blend-v1)*opacity;
}

```

Notice that `mix(vec, vec, bvec)` DO NOT work on most GL ES implementations, so just use it if you're working just with desktop. (But you can test it on mobile if you wish so)

EDIT: Here's an optimized version making use of swizzle masks and MADs (note the algorithm is the same, it was just rearranged.)

```
vec4 Overlay(vec4 v1, vec4 v2, vec4 opacity)
{
    const vec3 constants = vec3(1.0, 2.0, 0.5);
    bvec4 less = lessThan(v1, constants.zzzz);
    vec4 blendLow = v1 * v2 * constants.yyyy;
    vec4 blendHigh = constants.yyyy * (v2 + v1) - blendLow - constants.xxxx;
    vec4 blend = mix(blendHigh, blendLow, less);

    return v1 + (blend-v1) * opacity;
}

```
> 8 votes

---
Tags: shaders, glsl, optimization
---


title: Combine Two Shader Program

text:
# Question
Title: Combine Two Shader Program
For my android application, I want to apply brightness and contrast shader on same image.

At present I am using gpuimage plugin. In that I found two separate program for brightness and contrast as per the following.

Contrast shader:

```
    varying highp vec2 textureCoordinate;

    uniform sampler2D inputImageTexture;
    uniform lowp float contrast;

    void main()
    {
         lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);

         gl_FragColor = vec4(((textureColor.rgb - vec3(0.5)) * contrast + vec3(0.5)), textureColor.w);
    }

```

Brightness shader:

```
    varying highp vec2 textureCoordinate;

    uniform sampler2D inputImageTexture;
    uniform lowp float brightness;

    void main()
    {
        lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);

        gl_FragColor = vec4((textureColor.rgb + vec3(brightness)), textureColor.w);
    }

```

Now applying both of the effects I write following code

```
    varying highp vec2 textureCoordinate;
    uniform sampler2D inputImageTexture;
    varying highp vec2 textureCoordinate2;
    uniform sampler2D inputImageTexture2;
    uniform lowp float contrast;
    uniform lowp float brightness;

    void main()
    {
        lowp vec4 textureColorForContrast = texture2D(inputImageTexture, textureCoordinate);

        lowp vec4 contastVec4 = vec4(((textureColorForContrast.rgb - vec3(0.5)) * contrast + vec3(0.5)), textureColorForContrast.w);
        lowp vec4 textureColorForBrightness = texture2D(inputImageTexture2, textureCoordinate2);

        lowp vec4 brightnessVec4 = vec4((textureColorForBrightness.rgb + vec3(brightness)), textureColorForBrightness.w);
        gl_FragColor = contastVec4 + brightnessVec4;
    }

```

Doesn't able to get desire result. I can't able to figure out what I have to do next? So please friends help me in this. What program I have to write?

# Answer
Try:

```
varying highp vec2 textureCoordinate;

uniform sampler2D inputImageTexture;
uniform lowp float brightness;
uniform lowp float contrast;

void main()
{
    lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
    textureColor.rgb = ((textureColor.rgb - vec3(0.5)) * contrast + vec3(0.5));
    gl_FragColor = vec4((textureColor.rgb + vec3(brightness)), textureColor.w);
}

```

EDIT: The reason why your shader was not working, is because you were doubling the input too. If you think of it, the first shaders apply **ONE effect to ONE image**. When merging both, you'd expect **TWO effects on ONE image**. But what you tried to do was applying **TWO effects on TWO images**. You just had to get rid of the second texture and UV parameters, then apply both effects on the single texture remaining.
> 2 votes

---
Tags: opengl, android, shaders, andengine, fragment-shader
---


# Question
Title: change direction navmesh agent on collision encounter
I have one player and many enemies. The enemies are following my player through the navigation mesh. Sometimes enemies get stuck because there is another enemy in-front of them. You can say both are in line.

Is it possible that when one enemy collides with other enemy in-front of it to change direction so that it avoids colliding with one another?

# Answer
> 2 votes
This is an AI problem typically found in RTS games. Many of such games have solved the problem via different methods.

I personally like this article and the implementation follow-up article as an introduction into advanced pathfinding.

So, the answer is definitely a **yes**. Off the top of my head you could try some of the following:

* Check for local enemy collisions and repath one of the unit
* Check for local enemy collisions and move aside the unit that's blocking the way
* Implement a flow-field pathfinding algorithm (used by Supreme Commander 2), (theory, more practical paper)
* Implement a flocking algorithm like BOIDS which is pretty intuitive

---
Tags: navmesh
---