title: Vector2 always starts from origin

text:
# Question
Title: Vector2 always starts from origin
I am trying to create `Vector2` which starts from the players sprite and points towards other point. And I need its starting point to move along with player sprite. But however whatever I do all my vectors start from the origin and point towards the point I want. Is there any way to make `Vector2` to start from the

# Answer
All vectors 'start' at the origin. They are just directions. You can define a *ray*, which is two vectors together, one to define position (P) and one to define direction (D). Then you can find any point on the ray by using a scalar parapeter (t):

```
point_on_ray(t) = P + D * t

```

By anyway, from the sound of it that's not what you need. In your case, you just need a vector (V) to point from your player position (P) towards a goal point (G).

All you need to do is construct V every frame.

```
V = G - P

```

This is your direction vector. It starts at the origin but is in the *direction* the goal is to the player.

Finally, the length of this vector is the distance between player and goal. Often, you need a normalised vector wich has a length of 1 and is a pure direction. To do this you just divide all components by length. I don't know the library you are using in question, but they will have a 'normalize' or 'unit' method to do that.
> 3 votes

# Answer
This is a basic linear algebra question. A vector is the difference between two points, such that A + V = B. You can find the correct V by taking B - A. If you need both a reference point and the vector, you need to store both of them. The combination of a starting point and a vector pointing to an end point is a line segment, not just a vector. You can represent a point as a vector since A - 0 = A, hence a point is just a vector relative to the origin. If A is the player position and B is the target, V = B - A is the vector, and if you need to remember the player position, you'll just need to copy it into another variable.

At least until you get to affine transforms, where points and vectors have an additional component, 1 for points and 0 for vectors, such that the B - A = V equation works out to 1 - 1 = 0 for that component. Thus in 2D you can sti treat points as vectors, just remember that the origin is (0,0,1) so a point referenced by vector A comes to (0,0,1) + (x,y,0) = (x,y,1). Meaning that any math needing to do affine transformations will need to implicitly treat the extra component as 1 for vectors representing points and 0 for regular vectors. Same frameworks have an extra Point class to make all this automatic.
> 0 votes

---
Tags: libgdx
---


title: Attach Transform to another GameObject

text:
# Question
Title: Attach Transform to another GameObject
The scenario I am trying to accomplish is attaching a turret to a mount point on a ship. I have gotten as far as bringing in the prefab and assigning it as a child object with the following code:

```
GameObject leftFixedGun = (GameObject)MonoBehaviour.Instantiate(Resources.Load("Laser Fixed Gun"), leftMountPoint.position, leftMountPoint.rotation);
leftFixedGun.transform.parent = player.transform;

```

The problem is, it takes on the rotation of the mount point object, obviously, which isn't exactly what I'm going for.

I have a couple ideas of how to fix this problem, but would really like it to be a different solution all together.

My idea to fix this problem would be to rotate the transform at `leftGunMountPoint` in order to align the attached gun correctly.

The ideal solution, and the one I would like help with, would to be to align a local `mountPoint` transform I have under the `leftFixedGun` to a `leftGunMountPoint` under the ship I am trying to attach the gun to.

I hope this makes sense, and if it doesn't please feel free to leave questions in the comments. Also, please let me know if I am going about this completely wrong =)

Thanks!

EDIT:

Thanks to the answer, and if anyone else is wondering about this, easiest way to accomplish this is as follows:

* Create a transform, and line it up with where you want to place the item trying to be mounted.
* The following code attached the gun as I wanted.

`GameObject laserFixedGun = (GameObject)MonoBehaviour.Instantiate(Resources.Load("Laser Fixed Gun"), leftMountPoint.position, leftMountPoint.rotation);
laserFixedGun.transform.parent = player.transform;`

# Answer
> 1 votes
If I'm reading your question correctly, it sounds like you have a locator Transform for a point relative to the ship where you'd like to mount your turret. But if you attach it and fix the rotation to match the ship, then your gun is rotated the wrong way from how you had it when you made the prefab?

If that is indeed the case, the solution is to add another top-level GameObject to your "Laser Fixed Gun" prefab that you expect to parent to the ship, matching both the rotation and position like you have it.

But then within that prefab, the actual LaserFixedGun objects will be rotated in such a way that they look correct.

Assuming your prefab looks something like this:

```
v Laser Fixed Gun [ Transform, MeshRenderer, TurretScript]
  > Thrusters [ Transform, ParticleSystem ]

```

You'll want to change it to this:

```
v Laser Fixed Gun [ Transform ]
  v Laser Fixed Gun [ Transform, MeshRenderer, TurretScript]
    > Thrusters [ Transform, ParticleSystem ]

```

Using a child object in your mount point is possible but unintuitive with a transform hierarchy. Treating your top-level object as your mount point will make your life much easier.

---
Tags: unity
---


title: Circle inside circle collision

text:
# Question
Title: Circle inside circle collision
In one of my projects I have a game area in the shape of a circle. Inside this circle another small circle is moving around. What I want to do is keep the small circle from moving outside the bigger one. Below you can see that in frame 2 the small circle is partly outside, I need a way to move it back to just before it is about to move outside. How can this be done?

Also, I need the collision point along the arc of the big circle so that I can update the small circle's velocity. How would one go about calculating this point?

What I would like to do is before moving the small circle, I predict its next position and if it is outside I find the time of collision between t=0 and t=1 (t=1 full time step). If I have the collision time t then I just move the small circle during t instead of a full time step. But again, the problem is I don't know how to detect at that time the collision occurs when it comes to two circles and one being inside the other.

**EDIT:**

Example of collision point (green) I want to find. Maybe the picture is a bit off but you get the idea.

# Answer
Let's assume the large circle has centre `A` and radius `R` and the small circle has centre `B` and radius `r` moving towards location `C`.

There is an elegant way to solve this problem, using Minkovski sums (subtractions, actually): replace the disc of radius `R` with a disc of radius `R-r`, and the disc of radius `r` with a disc of radius `0`, *ie.* a simple point located at `B`. The problem becomes a line-circle intersection problem.

You then just need to check whether distance `AC` is smaller than `R-r`. If it is, the circles do not collide. If it is larger, just find the point `D` on `BC` at distance `R-r` of `A` and this is the new location of the centre of your small circle. This is equivalent to finding `k` such that:

```
  vec(BD) = k*vec(BC)
and
  norm(vec(AD)) = R-r

```

Substituting `vec(AD)` with `vec(AB) + vec(BD)` gives:

```
AB² + k² BC² + 2k vec(AB).vec(BC) = (R-r)²

```

Provided the initial position was inside the large circle, this quadratic equation in `k` has one positive root. Here is how to solve the equation, in pseudocode:

```
b = - vec(AB).vec(BC) / BC²    // dot product
c = (AB² - (R-r)²) / BC²
d = b*b - c
k = b - sqrt(d)
if (k < 0)
    k = b + sqrt(d)
if (k < 0)
    // no solution! we must be slightly out of the large circle

```

With this value of `k`, the small circle's new centre is at `D` such that `BD = kBC`.

**Edit**: add quadratic equation solution
> 10 votes

# Answer
Say the big circle is circle A and the small circle is circle B.

Check to see if B is inside A:

```
distance = sqrt((B.x - A.x)^2 + (B.y - A.y)^2))
if(distance > A.Radius + B.Radius) { // B is outside A }

```

If in frame `n-1` B was inside A and in frame `n` B is outside A and the time between frames wasn't too big (aka B wasn't moving too fast) we can approximate the point of collision by just finding the Cartesian coordinates of B relative to A:

```
collision.X = B.X - A.X;
collision.Y = B.Y - A.Y;

```

We can then convert this points to an angle:

```
collision.Normalize(); //not 100% certain if this step is necessary
radians = atan2(collision.Y, collision.X)

```

If you want to know more exactly at what `t` B is outside A for the first time you could do a ray-circle intersection every frame and then compare if the distance from B to the point of collision is bigger then the distance B can travel given it's current speed. If so you can calculate the exact time of collision.
> 4 votes

# Answer
Let (Xa,Ya) the position of the big circle and it's radius R, and (Xb,Yb) the position of the smaller circle and it's radius r.

You can check if these two circles collide if

```
DistanceTest = sqrt(((Xa - Xb) ^ 2) + ((Ya - Yb) ^ 2)) >= (R - r)

```

To find out the position of collision, find the exact time moment when the circles collide, by using a binary search but with a fixed number of steps. Depending on how your game is made, you can optimize this part of the code (i provided this solution to be independent of how the small ball behaves. If it has constant acceleration, or constant speed, this part of the code can be optimized and replaced with a simple formula).

```
left = 0 //the frame with no collision
right = 1 //the frame after collision
steps = 8 //or some other value, depending on how accurate you want it to be
while (steps > 0)
    checktime = left + (right - left) / 2
    if DistanceTest(checktime) is inside circle //if at the moment in the middle of the interval [left;right] the small circle is still inside the bigger one
        then left = checktime //the collision is after this moment of time
        else right = checktime //the collision is before
    steps -= 1
finaltime = left + (right - left) / 2 // the moment of time will be somewhere in between, so we take the moment in the middle of interval to have a small overall error

```

Once you know the collision time, compute the positions of the two circles at the final time and the final collision point is

```
CollisionX = (Xb - Xa)*R/(R-r) + Xa
CollisionY = (Yb - Ya)*R/(R-r) + Ya

```
> 0 votes

# Answer
I've implemented a demo of a ball bouncing in a circle on jsfiddle using the algorithm described by Sam Hocevar:

http://jsfiddle.net/klenwell/3ZdXf/

Here's the javascript that identifies the point of contact:

```
find_contact_point: function(world, ball) {
    // see https://gamedev.stackexchange.com/a/29658
    var A = world.point();
    var B = ball.point().subtract(ball.velocity());
    var C = ball.point();
    var R = world.r;
    var r = ball.r;

    var AB = B.subtract(A);
    var BC = C.subtract(B);
    var AB_len = AB.get_length();
    var BC_len = BC.get_length();

    var b = AB.dot(BC) / Math.pow(BC_len, 2) * -1;
    var c = (Math.pow(AB_len, 2) - Math.pow(R - r, 2)) / Math.pow(BC_len, 2);
    var d = b * b - c;
    var k = b - Math.sqrt(d);

    if ( k < 0 ) {
        k = b + Math.sqrt(d);
    }

    var BD = C.subtract(B);
    var BD_len = BC_len * k;
    BD.set_length(BD_len);

    var D = B.add(BD);
    return D;
}

```
> 0 votes

---
Tags: collision-detection
---


title: Are hidden stats a good idea?

text:
# Question
Title: Are hidden stats a good idea?
I'm thinking of and RPG, FPS or a turn based game (does not really matter), where the player does not know his character(s) exact stats. Of course they exist as random variables of normal distribution inside the game engine. So no visible HP bar, Level, ATK or DEF. You can only determine it's status by it's signs of life (good mood, fatigued, dying, dead, etc...). With regard to casting spells, when your mana is running low, your chance of failing to cast a spell increases (so there is no "zero" point when you need to find the next gas station for refill). To measure your skill you can battle with monsters which has always have fixed (but yet unknown) stats.

The stats would improve as you use them, but each character would have a random talent set so some skills can be improved easier than others.

So my question for the game devs and gamers, is making the true self of your character a mystery a good idea?

UPDATE:

From the answers it seems it depends on heavily the genre of the game.

For RPGs, I thought finding out what's good for your character is fun. From the responses, it seems it's not so fun because the players usually have an established play style and will try force it from their character for all costs.

The actual game idea I dreamed about is manager like game somewhat similar to the Pokemon game series. The main character has several champions and wanders around the virtual world and battles with others in an arena in a HOMM like fashion. And those champions would have the hidden stats. I didn't mentioned this in the original question because I don't wanted to bias the answers around this particular game concept.

For the feedback to the player (in both cases): There would be ratings similar to the elo ratings that a chess player has. One for the melee hitting, melee blocking, ranged hitting, ranged blocking abilities, and one for the magic abilities. Hitting the opponent with a sword will increase the melee hitting rating, if the enemy blocks the hit melee hitting decreases. If the opponent hit us with a sword, our melee blocking rating decrease, for successful block it increases, same for the ranged attacks. For the magic skill it's a bit tricky. High magic ability means: easier to cast spells successfully, harder to be affected by cursing spells, and easier to be affected by enchanting spells.

The standard abilities like hit points, toughness, strength, magic power, are estimated from the performance of the champion. These determine the actual damage dealt on successful hit. There would be "standard champions" that has a fixed and known stats, and the other champions' stats can be measured against them to bootstrap the system.

So if the player tries out all aspects of his champions he can find out the skillset his champions have, if the player don't like the skillset he can trade his champions to get the ones with skillset he likes.

UPDATE 2:

So to get straight to point: *Would it be fun if I center my game around the concept of getting to know your characters/champions, instead of serving all stats readily to the player?*

It would be similar to the football players. The coach will need to see how their players perform in various positions to assign them to position that's the best for them. So he will need to try each one as a goalkeeper, defender or forward. After several matches it will be clear which position is good for them.

# Answer
> 17 votes
This technique is called a black box. This is much more a style instead of a "right or wrong" decision that makes a game better or worse. As implied in the other answers, it can be done well or poorly.

There are two concerns of note.

1: First, you should be asking "why" you should blackbox, instead of whether it's a good idea or not.

Some games benefit from having the various statistics readily available. Players can more immediately and accurately determine if various components are desirable. The game can easily become a min-maxing fest if you aren't careful, but players generally feel more certain in their choices.

Also, any poor design choices related to statistics, such as a weapon you can only acquire late in the game with low stats, become more apparent and are easier to be found by testers and players after release.

Some games benefit more from blackboxing the math. If your focus is less on optimization, less on the statistics, and more on accessibility or some non-statistics-based mechanic that is central to the experience, hiding the stats would make more sense.

2: The second concern is that, if you decide to black box, you need to ensure that the player has some other form of feedback. Statistics are a (very basic) form of feedback. If you hide them, you must have some other form of feedback such that players understand the ramification of their decisions. As mentioned in other answers, visual feedback works (wounds, blood, red edges on the screen). Other options include audio, text, use of color, a means of experimenting with a frame of reference (a magic room in the menu ala Fable 3 with a "training room"), and more.

Creativity is a plus when creating other types of feedback, but whatever the form, it must suit the basic need of providing players with a means of weighing decisions. If the players can't see the "attack power" of two weapons, they need some way to decide ***and to feel certain the decision was right for them.*** If a player cannot see "Hit Points", he/she needs some means of feeling certain of the chance of risk for an encounter (not rushing in and finding out they were very close to death after they die).

Hope this helps

# Answer
> 14 votes
Hidden stats can be fun ***if done correctly***. It sounds like you are going in an interesting and unique direction which can land you in a very good place.

The problem I foresee is having random stats. While it sounds good on paper, it can yield very different results. Gamers have different play styles and if you force them out of what they are comfortable with, they can get frustrated. They may even resort to restarting the game multiple times when they discover their character isn't how they want it to be.

Maybe instead of random stats, you have them answer a quiz or perform actions on a vanilla character and base stats on the answers the player chooses or the actions they perform.

That way you can still have hidden stats but the player still has some control over how the character grows.

# Answer
> 8 votes
I think there is one very important aspect you have to deliver on and if you can then this is a perfectly good idea. And that is communication. The problem with abstracting over the numbers is that the difference may be very difficult or observe due to the manifesting over long periods of time or being very subtle. The number are an obvious if very crude way to communicative to the user exactly what is happening.

To touch on a few examples that you mentioned.

> With regard to casting spells, when your mana is running low, your chance of failing to cast a spell increases (so there is no "zero" point when you need to find the next gas station for refill).

If the player just stops working that is going to be very frustrating to the player. You need to communicate the mana levels somehow. You can do this by the character visibly changing or complaining more vehemently as the mana levels decrease.

> The stats would improve as you use them, but each character would have a random talent set so some skills can be improved easier than others.

This too has to be communicated or it is going to be really hard for the player to notice. Say if a character has a propensity for archery that should be built into their back story or they should volunteer or show enthusiasm for tasks they are talented at. So I think just a random talent set is a bad idea unless you can communicate the talents in some other way than observation or the player's trial and error.

# Answer
> 3 votes
The point of having variable stats in the first place is first and foremost that the player can increase those stats. It is a simple but effective skinner box technique. Second it gives the player some customization options, choosing what skill to level up feels like making an important decision, and that is good.

The downside of variable stats is that you need to design the game to be enjoyable no matter how the stats have developed. This can be quite hard as tuning a fight to the desirable difficulty for a player with one stat set will often make it either too hard or too easy for a player with a different stat set.

If a player can neither see nor influence a stat then what is the point of making it variable? As I see it you get the full effect of the downside, but none of the upsides.

# Answer
> 3 votes
> There would be ratings similar to the elo ratings that a chess player has.

A concern I would have with this system is this: ELO is based on number of games played. Which means that, initially, the player has no accurate information about their character(s). All they have are a bunch of people with random, hidden stats.

Indeed, ELO ratings are very misleading, because ELO is *relative*. If you're fighting a bunch of guys with low defensive stats, your attack ELO is going to be disproportionately high. In fact, if you have a lucky streak with the RNG, this can make a lower attack character look like a higher one.

Which means that, not only have you hidden information from the player (their actual attack rating), you are now *lying to them* by letting them think that their attack is higher than it really is.

This is purely subjective on my part, so bear with me. I feel that a videogame represents a social contract between the player and the game designer. The game designer provides a game, which displays information to the player. It is the player's job to see this information and interpret it. It is the game designer's job to make this information sufficiently clear for the player to be able to properly interpret it and make reasonable, meaningful decisions from it.

Game design, at its most core, fundamental level, is what any artistic endeavor is about: *communication*.

If I see that I have a high attack rating, I should expect that to be *legitimate information*. That is my right as a player, and it is the responsibility of the game designer not to infringe on that right.

I would consider it a **mortal sin** for a game to *deliberately* give me false information, especially info which is critical to my success. This is not misdirection or an unintended accident. This is *perfidy*: a game designer willfully and deliberately not acting in good faith.

And your ELO system can do exactly that, since ELO is an estimate that only gets better with the number of games played and the level of opponents faced.

It's one thing for a game to accidentally mislead you. Or for me to simply misunderstand a clue. But numbers are hard data. And if I have a high numerical value, I have every right to expect that this number is in some way *accurate*. Even if I don't understand what that number means exactly, I should expect that a character with 50 in some stat is at least somewhat better at that task than a character with 20 in that stat.

Break the social contract between yourself and your players *at your own peril*.

Furthermore, your ELO system encourages players to engage in more fights than they might want, just to get a more accurate idea of their ELO. I'm not a fan of a system that encourages the player to play in this way. I would prefer that the player want to play naturally, not has to be tricked into it just to get actual information about their character.

The thing you need to think hardest about is this: why do you *want* to hide these stats? What do you gain by it in terms of design? Or what behavior are you trying to *prevent* the player from being able to do? In short, what do you want your system to achieve that showing these stats makes harder or impossible?

Giving players (or people in general) information allows them to make more informed decisions. Thus, by denying them information, they must make due with less. This typically leads to more conservative behavior out of the player if losing has any real downsides. However, because the accuracy of their information is based on number of fights, it could lead to far more wild and experimental behavior, just to find out what a character's stats are.

Is this what you *want*?

# Answer
> 1 votes
With regards to your "pokemoon-esque" game idea- having your OWN champions' stats be hidden from the player at first seemed a BAD idea, or rather one that I didn't like at first... however, I HAVE always felt that games which were attempting to be as "realistic" as possible would ultimately not even want to use stats, per se. If your pokemon game were "real life", one would not have the convenience of having a numerical value for, say "strength" but rather one would have to judge its strength based upon one's own knowledge and familiarity with the thing. Perhaps someone who is an experienced trainer can end up with a result quite similar to a numerical value, but a novice surely wouldn't. So I thought, what about making the accuracy of your assessment part of the whole game. Like the trainer has stats which determine the accuracy of what you see as your champions stats. At first you might only be able to judge strength, at least perhaps until you train a champion that is, say, highly intelligent so raising it allows you to judge Intelligence as a value. Because you are able to judge it doesn't mean that you are able to judge it well, or even accurately so you would perhaps have a stat which corresponds to the likelihood of the judgement being inaccurate, as well as one for the severity of the inaccuracy.

So, while I think that it could be used in some really cool ways in your poke-champion style RPG, my general view on the matter would be that if you are making an RPG, include the stats. If you feel the numbers detract from the experience and want to make the character's status apparent through how he looks or how the control changes YOU ARE MOVING AWAY FROM THE TRADITIONAL RPG, which is fine however if you are making a real RPG which utilizes a stats system, you should at least give the player a screen where he is given the numerical values for his abilities and attributes. As the guy above me said (paraphrased) how exactly does your game BENEFIT from what you want to do differently- it is not enough to want to hide the stats simply because it would be cool to hide the stats. Also, it was said that giving people more information allows them to make more informed decisions... giving them TOO MUCH information- either by drowning them in too much data or by giving them unintentionally misleading or unclear data, is just as bad. One must strike a narrow balance, which is why the traditional style is so commonly used- it manages to strike that balance and people are already familiar with it.

I enjoy when there is an entirely new way of doing things with regards to the battle system in an RPG; however while I do enjoy the process of learning a well-designed, unfamiliar system I always end up feeling like I've finally got the hang of it right in time for the last battle... so, it's a balance. Hope this helped :)

---
Tags: game-design
---


# Question
Title: Implementing Frame of reference for physics calculations
How would I alter physical calculations to account for frame of reference of a physical body?

Currently I have a world that is a collection of rigid body objects that act on each other. There is no frame of reference for collision detection or resolution with respect to each body (i.e. body A has a velocity of zero when resolving a collision with body B and vice versa). The world is the reference frame, therefore everything is moving that has a non-zero velocity.

# Answer
If you need a calculation in object space for any reason, just multiply by the object's inverse transformation to find positions and orientations relative to that object. This makes the position and orientation of that reference object zero and identity. All object's positions and orientations will be relative to this reference object.

To calculate the relative velocities, just subtract the velocity of the reference object from the velocities of the other objects, to get their relative velocities, which again makes the velocity of your reference object zero, regardless of its world velocity.
> 1 votes

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


# Question
Title: Slick2d Particles loading xml returning null
I've made a particle class that creates a particle of Slick2d library, but the XML file doesn't want to load , it keeps giving me null error. I gave it the path as I do for everything but it refuses to work and its been like this for days I just cant get it to open that XML file. If anyone can help me it would be much appreciated.

```
try {
        particleImage = new Image("res/particles/particle.png", false);
        system = new ParticleSystem(particleImage,1500);

        //load the xml file and add the emitter to the system
        File xmlFile = new File("res/particles/bloodDown.xml");
        ConfigurableEmitter emitter = ParticleIO.loadEmitter(xmlFile);
        emitter.setPosition(315, 358);
        system.addEmitter(emitter);
    } catch (Exception e) {
        System.out.println("Exception: " +e.getMessage());
        e.printStackTrace();
        System.exit(0);
    }

```

Entire particle class : http://pastebin.com/rBR0xpE7

Particle manager class : http://pastebin.com/N8gNFk6W

Slick 2d documentation : http://www.slick2d.org/javadoc/

My structure of workspace:

# Answer
> 1 votes
You don't need to create a symbolic Java File to pass to the ParticleIO method, you can just provide the relative String reference to the path of the XML. ParticleIO is a class used for Serializing and Deserializing ConfigurableEmitters through XML. So if you are trying to "load" an XML using ParticleIO, then you are trying to deserialize that XML into a ConfigurableEmitter. For this to work properly it must have been serialized to that XML file first. If loadEmitter() is returning null and your path is 100% correct, then you are trying to deserialize an incorrect XML file.

---
Tags: java, slick, eclipse
---


# Question
Title: Weird behavior with XNA SpriteBatch.Draw origin
I have a texture with 256x256 pixels.

Consider this piece of code:

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }

```

If I run this, the texture appears (predictably) at the top-left corner of the window with the correct size (100x100).

If I do this instead (XNA 4.0-only):

```
spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White, 0, new Vector2(0, 0), SpriteEffects.None, 0);

```

Everything is still as expected. However, as soon as I change the origin parameter, the position gets weird.

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(texture, new Rectangle(0, 0, 100, 100), null, Color.White, 0, new Vector2(128, 128), SpriteEffects.None, 0);
        spriteBatch.End();

        base.Draw(gameTime);
    }

```

In this last example, only 1/4 of the texture is visible.

In other words, the origin parameter not only changes the origin of the rotation, but also the destination rectangle. In other words, the Top/Left coordinates of the rectangle are not the Top/Left coordinates of the drawn sprite, but rather the coordinates of the Origin.X/Origin.Y texture pixel.

If the target position was just a Vector2, I'd understand (and fully support) this behavior, but with a destination rectangle it just seems odd, especially since the documentation does not seem to mention this fact (although to be honest, the documentation barely says anything at all).

A StackOverflow answer even suggests that a destination rectangle with rotation doesn't make much sense, but XNA offers it anyway.

What is the reason for this behavior?

# Answer
> 5 votes
Though your question about `Draw` arguments is understandable, I do think it is by design. Also,

> the Top/Left coordinates of the rectangle are not the Top/Left coordinates of the drawn sprite, but rather the coordinates of the Origin.X/Origin.Y texture pixel.

This is an incorrect statement. Your origin has become the top-left **visible** pixel, which is governed by screen space, not by misdesign design of Spritebatch. The actual top-left pixel is simply off-screen.

For clarity, I put all your draws together into one screenshot, and I added some more with rotation. The black lines are gridlines at the `destinationRectangle` X and Y coordinates.

```
spriteBatch.Draw(texture, new Rectangle(100, 50, 100, 100), null, Color.White);
spriteBatch.Draw(texture, new Rectangle(100, 225, 100, 100), null, Color.White, 0, new Vector2(0, 0), SpriteEffects.None, 0);
spriteBatch.Draw(texture, new Rectangle(100, 400, 100, 100), null, Color.White, 0, new Vector2(128, 128), SpriteEffects.None, 0);

spriteBatch.Draw(texture, new Rectangle(400, 50, 100, 100), null, Color.White, MathHelper.PiOver4, Vector2.Zero, SpriteEffects.None, 0);
spriteBatch.Draw(texture, new Rectangle(400, 225, 100, 100), null, Color.White, MathHelper.PiOver4, new Vector2(0, 0), SpriteEffects.None, 0);
spriteBatch.Draw(texture, new Rectangle(400, 400, 100, 100), null, Color.White, MathHelper.PiOver4, new Vector2(128, 128), SpriteEffects.None, 0);

```

As you can see, your texture coordinate has not been changed. The destination rectangle has been moved (prior to rotating).

### Does that make sense?

I think so.

To answer your question, yes, the origin affects both the rotation center and the draw destination. But that alteration is completely logical. A preemptive summary: a destination rectangle does not make sense for a rotated quad, and `SpriteBatch.Draw()`'s arguments make as much sense as is possible.

Consider the process of drawing this sprite. Using your rectangle with position and size, `Spritebatch` generates a quad that it will toss into its "batch". That quad needs to be rotated about some point (there is no draw overload that includes rotation but does not include origin) For that idea to make sense, some vertices of the quad need to be rotated from behind or above that origin. But you didn't specify a position, you only specified a destination rectangle. That means that the top-left corner vertex (based on the X and Y of your rectangle) must be moved away from the rotation point, and that move is `-1 * origin`. This happens internally, without any extra work by you. Yes, it changes the "idea" of a destination rectangle. But the height and width don't make any sense after rotation either (they've both changed).

Compare that to the alternative. For every rectangle that you want to draw, in order to determine its position, you have to manually rotate the top-leftmost corner relative to your origin, then transform your rectangle's X and Y, then pass that new rectangle into the actual draw call. You do all all that work simply to make the `destinationRectangle`'s position match the screenspace position. In the meantime, the Rectangle's height and width are still wrong, because the rotation changed them, too. And some of your rectangle is farther left than your position value, so it was all for naught anyway.

Hopefully that makes sense. I am sure that most of your question came from the pixels that you thought had vanished (but were really just off-screen). If not, I'll be happy to argue about it more. :)

P.S. I am currently trying to roll some 2D physics, and I determined that `SpriteBatch` would cause more problems than it would solve exactly because of this kind of internal design decision. So I elected to generate quad vertices manually, to avoid my top-left point being transformed without my permission. But again, my trade-off for doing that is that I have to do much, much more work manually.

# Answer
> 0 votes
Your question is "What is the reason for this behavior?", right?

My guess is that the reason for this behavior is to render a texture rotated within an axis-aligned rectangle.

An example; Let's say you have a multiplayer-lobby in your game, and you want to be able to have simple chat there. You could make an easter-egg (fits the season, eh?!) that makes your avatar rotate by writing "/loop-de-loop" in the chat. As your UI has some nice frame around the avatar, this looks kinda crappy, so you use this draw-method to make sure the avatar does not go out of the bounds of its frame when rotating.

This might not be the most used version of Draw, but I can see its uses, if it works the way I understood from your post.

Edit; It's worth noting that for drawing a texture rotated freely, you are better off using one of the overloads where you specify position as a Vector2.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw.aspx

Edit2; ReRead your question and noticed that you also wonder why changing the origin changes the position of the texture within the rectangle? I will have to take a look at how that works when I get home to be able to give a better answer. I would have thought changing the origin didn't "move" the texture within the destination rectangle, so I have to try it out to see how it works and decide how/if it is usefull :P

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


# Question
Title: How do I detect when one sprite is moving away from another?
I'm currently working with crafty.js. I need to know how to detect when one sprite is moving away from another sprite.

# Answer
So I'm assuming you have an X/Y coordinate for each sprite, and some kind of loop that executes in your game. Given that, just calculate the distance between the two sprites each cycle in the loop. Compare the current distance from the distance in the previous loop, and if it is more, they are moving apart.

Something like this...

```
float old_distance = 0.0;
float current_distance = 0.0;

sprite A;
sprite B;

loop() {
   old_distance = current_distance;
   current_distance= sqrt((A.x-B.x)^2 + (A.y-B.y)^2);
   if (current_distance > old_distance) {
      // --- They are moving away from each other
   }
}

```

I believe you could just not do the square root calculation, as you really don't care about the exact distance, just whether one is farther away than the other. So just...

```
current_distance= (A.x-B.x)^2 + (A.y-B.y)^2;

```
> 2 votes

---
Tags: javascript, crafty
---


# Question
Title: How to alter the angle of texture projection
I'm currently working on a 3Dish game; it's on a grid, with 3D props and the camera looking down on the grid at about 45º, but I want to use 2D sprites for the player and NPCs.

Currently, I'm using a quad as a canvas, but I've run into some problems. If the quad is coming up vertically from the floor, foreshortening squashes the player. If I tilt the quad to the same angle as the camera (manual billboarding), the player looks fine but will clip through 3D objects to the "north" from the camera on the grid. I've looked into point sprites but it seems like these would have the same problem.

So, tilting the canvas is out. I need the player to be able to go in front and behind things.

My latest and most promising attempt was to turn the vertical-oriented square canvas into a trapezoid, to compensate for the perspective change. (The canvas is 32x32; at a 45º angle it ended up having a top length of 28.14 and a height of 39.68.) This gets me a square canvas again, but the texture isn't right. It ends up slightly squashed; on nearest-neighbour sampling it loses a row of pixels in the middle (on the character where it's noticeable) and gains one somewhere at the top (above the character's head...)

My maths on the trapezoid might not be exact, but this doesn't really seem like the right answer for keeping things pixel-perfect. Is there a way to use that canvas quad as, I don't know, like a window onto another rendering context which would be pixel-perfect?

Context: This is in Python, PyOpenGL and Pygame; the maximum GLSL version my computer can handle is 120 so it's openGL 3-ish but not quite.

# Answer
For the sake of anyone stumbling across this later, here is what I did.

In the GLSL Fragment shader, it outputs a constant after main() called gl\_FragDepth, which will be set to gl\_FragCoord.z unless you change it.

So, with some trial and error, I discovered the magic number was 0.0006, and set it per-vertex, so the top two had this and the bottom two had 0. So now in my fragment shader under the texture coord is this line:

```
gl_FragDepth=gl_FragCoord.z-depth;

```

The fragment shader smoothly interpolates this from the values set in the vertex shader, and my polygon appears straight. However the 0.0006 system only works if the camera's depth is always the same, so is the camera ever moves closer to the player I need to work out how to make it relative to gl\_FragCoord.z, rather than absolute.
> 0 votes

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


title: MVC with looping view

text:
# Question
Title: MVC with looping view
For our school project we'd like to develop a game using the MVC pattern. We're all moderate new java programmers and absolutely new in game development.

With our current view (containing only menu) using swing we have no issues. But we'd like to make the menu navigation within the game loop. And there's the issue: The game loop prevents the controller to continue. The solution sounds easy, but the implementation lacks some of my/our knowledge, additional thread. I think using a separate thread for view makes handling all stuff threadsafe difficult.

Our game loop is based on nifty, which is using slick2d and this is based on lwjgl (and so on). Reverting to swing does not solve our issue, because once we're in the real game loop, the situation would be the same (so far I understand).

I hope it is understandable without posting huge amount of code. Two questions comes to mind: How should threading be done, when my current try is having a (looping) view instance in its own thread? (Reading a bit here on gamedev seems to call our architecture in question) Is MVC the right choice if we're using slick as framework?

# Answer
Threading

I suggest you use just one thread for now. In my opinion, using multiple threads for rendering and game interactions will only complicate your code and introduce synchronization overhead, so the only time I would do that is if I MUST improve performance by using multiple threads for multiple CPUs (in which case you should profile first before optimizing). **However**, you should still keep your code modular which is where MVC comes in.

MVC

The main idea that you should take from MVC is to separate rendering logic and game logic. The Model maintains state information about the game and View simply reads that state from the Model and render it. Controller should be hooked up to handle input and modify the Model as well as initiating the update on the View.

A good example of a single thread MVC-ish game is https://github.com/libgdx/libgdx/tree/master/demos/superjumper/superjumper/src/com/badlogicgames/superjumper

It's based on LibGDX (cross platform Java game library).
> 1 votes

---
Tags: java, lwjgl, multithreading, slick, mvc
---


title: procedural height map that changes

text:
# Question
Title: procedural height map that changes
This a a weird question.

I'm making a game in unity. I have a grid of columns and the height of the columns is changing (lerping) randomly (just cus it looks cool!) I was wondering could I procedurally generate some sort of 2d contour map, then each column would take its height from the contour map, that way nearby columns would be similar in height. Also how would I then get this contour map to fluctuate and change randomly?

If my grid of columns is 10x10 that means this contour map can also be just a 10x10 array with only 100 data points. Can anyone think of a cheap way of achieving something like this?

# Answer
> 0 votes
Overlay a grid on every n'th cell horizontally and vertically, and initially assign each of theses a random value. Interpolate the remaining cells to get the smoothness you are after. On every m'th cycle assign a new random height to each overlay cell, but migrate to it over the full m cycles.

A refinement would be to "roll" the timing of assigning new target heights across the map, one row (or column) at a time.

This should give you a nice smooth "rolling" effect for your terrain. By tuning the parameters a bit the effect would give your characters time to react to changes, while having to remain alert

---
Tags: heightmap, procedural
---


title: Inventory View Screen

text:
# Question
Title: Inventory View Screen
Looking to create an inventory screen in Unity, and trying to think of the best way to do it.

My current line of thinking is having a few rows of squares for inventory items that are drag and droppable onto a paperdoll, a la Diablo. When dragging and dropping on the items, it would update a 3D model of your current playable object with the items.

The menu itself would be easy enough to do with a simple square and a hierarchy of game objects for the items, each responding to mouse hovering over.

The problem I am trying to figure out is being able to render the 3D model on the side. Granted, this is a nice to have, and not necessarily a need, but browsing the documentation, the only way I can think of accomplishing this is using a render to texture which requires Unity Pro with a separate camera completely out of bounds of the current space.

Anyone have suggestions on how to accomplish this?

# Answer
> 3 votes
I will attempt to answer this as best I can.

The easiest way to accomplish this would be to have another camera set up somewhere in your scene, enabling and disabling it when you need to render the inventory. I applied a different layer to the camera to render separate from my main view.

Hope this helps, there's a pretty good answer over on the Unity Q/A page.

http://answers.unity3d.com/questions/303620/rendering-3d-objects-on-the-gui.html

---
Tags: unity, gui
---


# Question
Title: Calculating an orbit and approach velocties
I have drones in my game that need to approach and orbit a node and shoot at it. Problem is I want to stay away from a real physics simulation, meaning I don't want to give the node and drone a mass and the drone's thrusters' a force. I just want to find the best way to approach and then enter orbit. There was a pretty good answer about using bezier curves and doing it that way, but that is essentially a tween between two fixed points. The nodes are also moving as the drones enter orbit.

# Answer
Remember that, at least in terms of gravitational pull (and not, say, collision), mass is only necessary to determine gravitational strength, and that is only necessary to determine acceleration of other objects toward the mass. And force is only necessary to determine acceleration, which is already known/calculated in this situation.

Thus, it's fairly straightforward to "fake" physics without doing a complicated simulation. You only need to alter acceleration of the drone to "fake" the gravity of the node.

The drone's acceleration (that is self-applied) should be altered by an acceleration vector before being applied to the velocity/position according to the direction of the node and the distance to the node. The direction of the acceleration vector is the direction of the node, and the magnitude is the inverse of the distance. This would simulate the gravitational pull of the node, as drones would be pulled faster towards nodes the closer they are.

The drone must, of course, change its orientation (and thus, acceleration) towards the orbit it wishes to establish (but this is a tangential AI concern). However, if no orbit was desired, this system would even fake the gravitational pull nodes would have on drones that are trying to fly away from them.

The specific algorithm for the acceleration depends on the implementation specifics, such as the drone accelerations and velocities. Testing with a simple run-time input can allow you to quickly determine the acceleration needed to get the right "feel".

This would even result in an eventual circular orbit, as long as the drone continually accelerates itself in the direction of the orbit's tangent, and the node continually "pulls" it inward.
> 1 votes

---
Tags: java, physics
---


title: Comparing two tree structures

text:
# Question
Title: Comparing two tree structures
I'm having a hard time trying to describe this in correct terms so I will just give as much detail as possible and hopefully someone knows what I'm trying to do =-)

I am trying to compare two node trees to determine how similar/different they are structure-wise. In my diagrams below, both examples have the same number of children, grandchildren, etc. In example 1, Root has a child with two children, but in example two, root does not.

I could probably figure out how to recursively loop through and count how many of each level there are and compare that, giving me an idea of how similar the trees are, but only doing it that way, it will look like they are identical, but in fact they aren't.

Anyone happen to know about this? Or even what the technical term for what this is?

**Edit:** Also, this is in C# and I am using Lists to store these objects and their children.

**Example 1**

**Example 2**

# Answer
What you are looking for is Rooted Tree Isomorphism, which is a specialised version of the Graph Isomorphism, except for trees and the root node is fixed.

The explanation given in this assignment uses two properties:

* Have the same number of levels (distance between root and leaf nodes)
* Each level has the same number of nodes

Using these two properties, work your way up from the leaves to the root, labelling each node with the number of children, in lexicographical order. For example, your Root in Example 1 will be labelled (0, 0, (0, 1)) - it has three children, the first/second have 0 children, and the third has 2 children which have 0 and 1 children respectively. Finally you just compare the root labels to see if the trees are the same.

I haven't done this kind of subject and I've only read this paper a few minutes ago so I can't vouch for its correctness; hope it helps anyway.
> 12 votes

# Answer
The problem to see if two graphs are logically the same is called Graph Isomorphishm so you might want so start from there.

Note that the general Graph Isomorphism problem is in NP however for this special case there might be a shortcut, I'm not sure since it seems logical that to know the differences you have to check if they are equal.
> 4 votes

---
Tags: algorithm, data-structure
---


title: Behavior Trees and Animations

text:
# Question
Title: Behavior Trees and Animations
I have started working on the AI for a game, but am confused how I should handle animations. I will be using a Behavior Tree for AI behavior and Cocos2D for my game engine.

Should my "PlayAnimationWalk" just be another node in the tree?

Something similar to this: \[Approach Player\] \- Play Walk animation \- Move Towards player \- Stop Walk animation

Or should the node just update an AnimationState in the blackboard and have some type of animation handler/component reference this for which animation should be playing?

This has been driving me nuts :)

# Answer
While it is, of course, possible to implement animations within an AI architecture, it would be a poor methodology for a number of reasons.

One such reason would be an agent that chooses to walk but cannot for some reason. Another reason would be needless complexity (many decisions would have to implement an exact-copy of an animation node because they all result in the same sort of behavior). Most importantly, however, is that your pathfinding will not be handled in the behavior tree, and **the pathfinding algorithm is what will actually implement agent movement**. Remember that the AI is only meant as a means of decision making, not implementing those decisions in the world.

A much more appropriate solution would be to tie the walking animation to the method that adds velocity to the character, which would be the pathfinding algorithm. This would implement the walking animation, or could implement a different animation for a different form of movement (running, crawling, teleporting, flying). It would be able to handle obstruction, difficulty in determining a path, and more all of which should interrupt any walking animation occurring. And it would simplify your behavior tree significantly, which is incredibly important for readability and debugging.
> 1 votes

---
Tags: architecture, animation, ai, behavior, tree
---


title: Calling opengl32.DLL from java?

text:
# Question
Title: Calling opengl32.DLL from java?
I don't like LWJGL in some cases, so I prefer to use Swing. The thing is that Swing doesn't have OpenGL. I have tried JOGL and it's a mess to install, needs external jars, and I have yet to get it working. So I was wondering if I could just make an OpenGL class that uses opengl32.DLL and put the graphics into a window made with Swing? Also, is opengl32.DLL able to be called with a 64 bit Java program?

# Answer
If you use a build system like MAVEN it is actually fairly easy to use JOGL. (But it is indeed stupidly hard to configure without it).

Just add this to your POM file

```
 <dependencies>
   <dependency>
     <groupId>org.jogamp.gluegen</groupId>
     <artifactId>gluegen-rt-main</artifactId>
     <version>2.0-rc11</version>
   </dependency>
   <dependency>
     <groupId>org.jogamp.jogl</groupId>
     <artifactId>jogl-all-main</artifactId>
     <version>2.0-rc11</version>
   </dependency>
 </dependencies>

```
> 3 votes

# Answer
JOGL does just that, but makes it easier for you. If you have trouble installing JOGL, you will have a lot more trouble trying to do it yourself. If you still insinst on doing it yourself, search for JNI and/or JNA.
> 0 votes

---
Tags: opengl, java, jogl, swing
---


# Question
Title: How do I implement branching dialogue in javascript?
I'm making a very basic visual novel type of game in JavaScript. I'm a beginner, so I'm just doing this for fun and learning, and due to bad planning I have run into a bit of a problem when you get to a branch in dialogue.

Currently I hold the script for the game in a string variable and I break up each scene with a tag such as "#~" into smaller arrays so that the game script looks like this:

```
var script = "Hello World!#~How are you today?"
var gameText = script.split("#~");
//gameText[0]= Hello World!

```

This works great for linear stuff, but how should I handle a branch in the dialogue tree? This method seems very complicated, as I would have to know exactly how long each path is and then if I ever needed to change anything it would be a headache.

How can I do this in a simpler way? I'm trying to stick to vanilla JavaScript as I'd like the game to work with Web Run Time.

# Answer
> 10 votes
Philipp's answer already shows the right direction. I just think the data structure is needlessly verbose. Shorter texts would be easier to write and read.

Even if shorter texts would make the algorithm a bit more complex, that's worth doing, because you only write the algorithm once, but most of your time will be spent writing and maintaining the story. Therefore optimize for making easier the part you will spend most time doing.

```
var story = [
  { m: "Hi!" },
  { m: "This is my new game." },
  { question: "Do you like it?", answers: [
    { m: "yes", next: "like_yes" },
    { m: "no", next: "like_no" },
  ] },
  { label: "like_yes", m: "I am happy you like my game!", next: "like_end" },
  { label: "like_no", m: "You made me sad!", next: "like_end" },
  { label: "like_end" },
  { m: "OK, let's change the topic" }
];

```

Some explanations for this design:

The whole story is written in one array. You don't have to provide numbers, they are provided automatically by the array syntax: the first item has index 0, the next one has index 1, etc.

In most cases, it is not necessary to write the number of the following step. I assume that most lines of text are *not* branches. Let's make "the next step is the following item" a default assumption, and only make notes when it is otherwise.

For jumps, use *labels*, not numbers. Then, if you later add or remove a few lines, the logic of the story will be preserved, and you don't have to adjust the numbers.

Find a reasonable compromise between clarity and shortness. For example, I suggest to write "m" instead of "message", because that will be the most frequently used command ever, so making it short will make the text more legible. But there is no need to shorten the remaining keywords. (However, do as you wish. The important thing is to make it most legible *for you*. Alternatively, you could support both "m" and "message" as valid keywords.)

The algorithm for the game should be something like this:

```
function execute_game() {
  var current_line = 0;
  while (current_line < story.length) {
    var current_step = story[current_line];
    if (undefined !== current_step.m) {

      display_message(current_step.m);
      if (undefined !== current_step.next) {
        current_line = find_label(current_step.next);
      } else {
        current_line = current_line + 1;
      }

    } else if (undefined !== current_step.question) {

      // display the question: current_step.question
      // display the answers: current_step.answers
      // choose an answer
      // and change current_line accordingly

    }
  }
}

```

By the way, these ideas were inspired by Ren'Py, which is not exactly what you want (not JavaScript, not web), but could give you some cool ideas anyway.

# Answer
> 5 votes
I would recommend you to create an array of dialog events. Each event is an object containing the text the NPC says and an array of possible player responses, which in turn are objects with a response text and the index of the event which follows on this response.

```
var event = []; // create empty array

// create event objects and store them in the array
event[0] = { text: "Hello, how are you?",
             options: [    { response: "Bad", next: 1 },
                           { response: "Good", next: 2 }
                      ]
           };
event[1] = { text: "Why, what's wrong?",
             options: [    { response: "My dog ran away", next: 3},
                           { response: "I broke up with my girlfriend", next: 4}
                      ]
           };
event[2] = { text: "That's nice",

...

```

# Answer
> 2 votes
You should use a different approach. JavaScript supports arrays and objects, so why not using one per entry, saving you all the splitting and also making the actual text easier to edit/read?

If you want, you can have a look at some prototype I've made during a few hours for #1gam. The source is free to be used under GPLv3 (I'm perfectly fine if you don't stick to the GPL, if you're just using it for inspiration. But let me know once your game is finished.). Just don't expect awesome writing or anything like that. ;)

To give a short explanation on how the code works, ignoring the CSS animation things and stuff like that:

* `var data` essentially contains the whole story with all possible choices, etc.
* Every "location" (or page/entry) is identified by an ID. The first ID in the list is `start`, the second `cwait`, etc.
* Every location contains two mandatory elements: A caption as well as the actual text. Links for decisions are written in some simple markup taking the form `[target location:display text]`.
* The whole "magic" is Happening inside `navigate()`: This function makes the Markup links clicky. It's a bit longer, because I'm also handling some static text for dead Ends there. The important part are the first two calls to `replace()`.
* The optional last entries define new background colors to blend to, supporting the overall mood of the game.
* Instead of defining these colors you could as well add links pointing to other locations (note this is **not** handled by my code; it's just some idea to demonstrate this):

`'start': ['Waking up', 'You wake...', 'cwait:yell for help', 'cwait: wait a bit', 'clook: look around']`

---
Tags: javascript, text-based, dialogue-tree, visual-novel
---


title: making different kind of bullets

text:
# Question
Title: making different kind of bullets
I have an enemy which shoots 3 different kind of bullets. They are of different sizes, speed, and representation (rectangle, oval, and a more classic bullet).

Should they be 3 separate classes or just 1?

If a single class, how would I implement it?

# Answer
This is a really hard question to answer properly, because it really depends on the actual use case, your implementation, etc.

The more similar the behavior is, the more likely you could handle them all with one class, but due to this not necessarily being the case, other options might be more interesting.

E.g. if the only difference is their speed or appearance on screen, simply using some member variable might be enough for Differentiation (although being not 100% perfect). If you've got different behavior as well (e.g. pathing, passing through things, etc.), using separate classes might be the best way to go.

On the other hand, if you're using some kind of component/system based approach to entities, just changing affected components might be the best Thing to do.

In short: The bigger/more complex the differences, the more likely it's useful to split the logic into its own class/entity type.
> 3 votes

# Answer
It can be 1, it can be 3, it could even be more. This is a design decision that you need to make, based on a number of factors. Some of them are soft decisions based on your circumstances and preferences:

* How much functionality (data and behaviour) is shared between the different types of bullets?
* How large and complex is the project going to be in the end?
* Where do your architectural tastes lie: do you flinch at the thought of having multiple small classes which only differ a little bit?

To answer the first point, it seems to me like a fair bit of functionality is going to be shared among the 3 types of bullets, unless my assumptions are wrong. It's a good bet that they will have a position vector, a velocity vector, a size property, some way of drawing themselves on the screen, and some way of detecting collisions.

This is a pretty good indication that you should start by having a "Bullet" class, which implements many of these things. One option available after this would be to inherit from Bullet, so e.g. OvalBullet could inherit from Bullet and implement its own Draw() method. In turn, you may already have a class in your project which is even more simple than "Bullet", e.g. an "Entity" class. Bullet could in turn inherit from there.

One important area where your bullets *may* differ is in collision detection. You could of course implement the exact collision detection code in OvalBullet, RectangleBullet, etc, but after a while you'll notice that you are duplicating code. Many different things will want to use either a box or a circle for collision detection. You might want to refactor the collision logic into several classes like RectangleCollisionDetector, CircleCollisionDetector, etc.

At this point, the job of a class like OvalBullet would be something like: correctly configure the relevant collision detector upon construction, pass the relevant parameters to the base (Bullet) constructor, and implement any truly unique behaviour (e.g. custom drawing). This way you can reduce duplication in your code, and make a trade-off between having shorter classes, but more of them interacting to achieve the outcome (hence my comment about your own preferences). The most basic, monolithic implementation might be 1 class. On the other end of the spectrum, this might be split into 2 base classes, a couple of interfaces, 2 or 3 collision detection classes, and 3 bullet classes.
> 3 votes

---
Tags: architecture, physics
---


title: Ways to achieve path finding on android

text:
# Question
Title: Ways to achieve path finding on android
I have spent two weeks on this task and its to no avail,i hope your expertise can help me.

I want to create a simple set of activities that allow the shortest path to be calculated between two points on a tile based map.The ANDROID game /project should allow:

> User to select there starting position i.e tile (x,y) and their ending position i.e tile(x,y)
>
> The path should then be drawn and I want the path drawn to have clickable tiles(which i will assign) so that i can display a popup to the user i.e (you just walked over a golden coin)-i require no score or any of that functionality.
>
> I want the ability to navigate between floors somehow.
>
> I want blockages to be in place(which i set) and which the algorithm understands and recalculates
>
> Lastly i want the user to have the choice of selecting the shortest path or not.

Can anyone help me on this with tutorials or even provide me with a short example.Its relatively simple I just don't have the skills you guys do to put it in action.I have found JAVA based examples but I don't know how to convert these to android.

Thanks in advance

# Answer
If you're having trouble with A\*, I suggest the following. It talks about the very basics and is applicable for any language/platform: A\* for beginners.

For how to handle click events in Android, please review this: Input Events

There are many ways to render graphics. Here are two links which talk about it indepth. Canvas and Drawables. Animation and Graphics.
> 1 votes

---
Tags: android, path-finding
---


# Question
Title: Game code structure using openGL / Android
My game will have 3 activities (splashscreen, options menu and main game).

As it stands, each is a separate activity with it's own activity class and GLSurfaceview class.

Is this structure the right way of doing things?

Secondly, I wish to load all my bitmaps in my Splashscreen activity 'up front' but if I do this, how exactly do I access / reference them from other classes / activities?

Appreciate if someone could clear this up for me.

# Answer
> Is this structure the right way of doing things?

Nothing wrong with that setup. I'd just be careful about the Splash screen. Splash screens (for Android) are meant as a temporarily placeholder to show that something is loading. If your App takes less then a second to load, then you shouldn't have a splash screen. Too many people make splash screens when they truly aren't needed. Here's some interesting info about Android splash screens.

You can load all your bitmaps by extending the Application class. In a way, it can provide global variables that persist between Activities. Generally, not a good practice for Android Apps, however games can be a good exception. Here's a link. Extending Application.
> 1 votes

---
Tags: android, opengl-es2, data-structure, assets, architecture
---


title: Animating a 3D model with XNA

text:
# Question
Title: Animating a 3D model with XNA
How do I animate a biped model from 3ds max using XNA framework or not necessarily the biped model, it could be any 3D model but how can I code the animation?

# Answer
Simply **export your annimation from 3DS Max** to a file type by supproter "XNA" (**fx, fbx, etc. ..)** And import your annimation in your project xna with "importer". (see the sample in the use of Microsoft Skinned model annim sample).

Many existing tutorial to convert a model from 3ds Max to annimé xna .. Here is one:

Tuto 3ds Max to Xna model anim
> 2 votes

---
Tags: xna, animation, 3d-meshes, 3dsmax, biped
---


# Question
Title: Game Engine for quick Horror Survival prototype
for a University project we need to develop a prototype for a Survival Horror game using an engine of our own choice. We are currently preparing the project and wondering which engine to use. Maybe your experience could be useful to us. The main aspects are:

* **Ease of use.** We are a team of 5 people with very little experience and have to finish the project in a short time. A flat learning curve and fast results are very important for us.
* **Dynamic lights and shadows.** The protagonist will carry a candle, which is one of the major gameplay elements. We need a system for dynamic lights and shadows.
* **Good sound system.** A lot of the horror will come from 3D sound effects, which the engine should support natively.
* **Free for personal / educational use.** Poor students living off packet soup already, you know :)

Unity was our first choice, but doesn't support dynamic shadows in the free version. We're just trying UDK, but are still looking for other possible solutions.

What engine do you think would be best suited for the task? Any hints are welcome!

Thanks, Daerst

# Answer
you should probably check out an engine like the half life engine, it is easy to use and some of the most fun horor games come from it, if you had good experience with game design then i would have suggested the havok engine if possible, its a go to for good game design, and great games use it because of how flexible it is for devs but again i suggest you use the half life engine unless you want to start from the ground up with havok(which is a more complicated engine, but allows for more manipulation)if you dont know how to start i cant tell you, or the question will probably close. please note im not a professional but i have some experience with this (i work mainly with more complicated engines) i dont know much about simple engines but havok, half life, Skyrim and portal engines are the engines i started out with. (disregard Skyrim and portal engines for a horror game)anyway, good luck
> 2 votes

---
Tags: lighting, shadows
---


title: XNA rendertarget sprite batch problem

text:
# Question
Title: XNA rendertarget sprite batch problem
When using this code:

```
public static Texture2D ShowHealthBar(SpriteBatch spriteBatch,Texture2D empty, Texture2D full, float health)
    {

        spriteBatch.Begin();
        RenderTarget2D healthBarTarget = new RenderTarget2D(Game1.graphics.GraphicsDevice, full.Width, full.Height);

        Game1.graphics.GraphicsDevice.SetRenderTarget(healthBarTarget);
        spriteBatch.Draw(empty, new Vector2(0, 0), Color.White);
        Game1.graphics.GraphicsDevice.SetRenderTarget(null);

        spriteBatch.End();
        return (Texture2D)healthBarTarget;
    }

```

the texture is purple.

When inserting Game1.graphics.GraphicsDevice.Clear the texture has the clear color.

Why doesn't the sprite batch work?

# Answer
The default behavior of `SpriteBatch` is to save its actual call to the GPU until you call `.End()`, rather than immediately (available by optional argument) when you call `.Draw()`. This allows it to reduce the total number of draw calls it makes, which is an important optimization. But switching the render target back *before* calling `End()` means that the draw goes to the wrong place, not the `RenderTarget` that was set when you called `Draw()`.

So, call `End()` before switching the target back to the default.
> 1 votes

---
Tags: xna-4.0, spritebatch, rendertargets
---


title: Getting an angle in degrees from north

text:
# Question
Title: Getting an angle in degrees from north
This may have been asked already, but I was unable to find it, because I don't really know what I'm looking for. I drew a picture:

I need *theta*. I've seen various solutions using `Vector.Dot`, and `Math.Atan2`, but they don't seem to work...

BTW, I need the output in degrees. On previous tries, I ran my results through `MathHelper.ToDegrees()`, but got values over 360, which shouldn't be possible.

This is my current code:

```
    Vector2 mouse = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
    Vector2 delta = mouse - Position;
    angle = Math.Atan2(delta.X, -delta.Y);
    angle = MathHelper.ToDegrees((float)angle);

```

EDIT: A little more info. I'm making a 2D game, and need the angle to 'rotate' one of my sprites (simply changing which sprite I'm displaying). The code for how I'm doing this is below.

```
public static Direction GetDirection(double radians)
        {
            if (radians > GetRadians(Direction.Up).Lower && radians < GetRadians(Direction.Up).Upper)
            {
                return Direction.Up;
            }
            else if (radians > GetRadians(Direction.UpRight).Lower && radians < GetRadians(Direction.UpRight).Upper)
            {
                return Direction.UpRight;
            }
            else if (radians > GetRadians(Direction.Right).Lower && radians < GetRadians(Direction.Right).Upper)
            {
                return Direction.Right;
            }
            else if (radians > GetRadians(Direction.DownRight).Lower && radians < GetRadians(Direction.DownRight).Upper)
            {
                return Direction.DownRight;
            }
            else if (radians > GetRadians(Direction.Down).Lower && radians < GetRadians(Direction.Down).Upper)
            {
                return Direction.Down;
            }
            else if (radians > GetRadians(Direction.DownLeft).Lower && radians < GetRadians(Direction.DownLeft).Upper)
            {
                return Direction.DownLeft;
            }
            else if (radians > GetRadians(Direction.Left).Lower && radians < GetRadians(Direction.Left).Upper)
            {
                return Direction.Left;
            }
            else
            {
                return Direction.UpLeft;
            }
        }
public static Radians GetRadians(Direction direction)
        {
            Radians r = new Radians(0,0);
            switch (direction)
            {
                case Direction.Up:
                    r = new Radians(15 * increment, increment);
                    break;

                case Direction.UpRight:
                    r = new Radians(1 * increment, 3 * increment);
                    break;

                case Direction.Right:
                    r = new Radians(3 * increment, 5 * increment);
                    break;

                case Direction.DownRight:
                    r = new Radians(5 * increment, 7 * increment);
                    break;

                case Direction.Down:
                    r = new Radians(7 * increment, 9 * increment);
                    break;

                case Direction.DownLeft:
                    r = new Radians(9 * increment, 11 * increment);
                    break;

                case Direction.Left:
                    r = new Radians(11 * increment, 13 * increment);
                    break;

                case Direction.UpLeft:
                    r = new Radians(13 * increment, 15 * increment);
                    break;
            }

            return r;
        }

```

# Answer
Two parts: 1. coordinate systems for angles can be...finicky. 2. You don't really need degrees for anything, with the possible exception of outputting their value to the user interface.

### Coordinate system angles

So you want an angle from "North", and judging from your example math, that means the -Y direction (in sprite coordinates with the origin in the upper left). Also judging from your example, you want it to grow clockwise. That's fine, although it varies from math convention slightly, which starts the unit circle pointing right and grows counter-clockwise. So instead of using a function that expects normal coordinate systems (and reversing the arguments you pass into it), use plain `Math.Atan()` instead.

There are surely elegant ways to deal with angles in any convention and coordinate system. But I have yet to find one. There always seem to be troubles when angles switch from one sign of angle to another. In order to avoid headaches with different cut-offs between the various ranges of output of trigonometric functions, I suggest you build a logic switch per quadrant. Quadrants can be from North to East, East to South, South to West, and West back to North. Like so:

```
// assert (delta != Vector2.Zero)
double angle = 0;
if (delta.X >= 0) {
  if (delta.Y > 0) {
    //quadrant 1
    angle = (0 * PI) + Math.Atan(delta.X / delta.Y);
  } else if (delta.Y < 0) {
    //quadrant 2, arctan will yield negative values, so work back from "South"
    angle = (1 * PI) + Math.Atan(delta.X / delta.Y);
  } else {
    // maybe Math.Atan2 handles the case of y=0.  But why leave that to chance?
    // due East
    angle = (1/2 * PI);
  }
} else { // (delta.X < 0)
  if (delta.Y < 0) {
    //quadrant 3, both coordinates negative, arctan will yield positive values
    angle = (1 * PI) + Math.Atan(delta.X / delta.Y);
  } else if (delta.Y > 0) {
    //quadrant 4, arctan gives negative values, angle increases toward 2PI
    angle = (2 * PI) + Math.Atan(delta.X / delta.Y);
  } else {
    // due West
    angle = (3/2 * PI);
  }
}

```

### Using radians like the universe intended

Ok, now you have a useful angle that is guaranteed to range from 0 to 2PI. It is in natural units, so you can apply all kinds of extra math on it quickly and efficiently using normal trigonometry functions. You get this advantage because you didn't stop to prematurely convert your angle into arbitrary, weird, and non-useful units called degrees. But if you really, really must display that unit to the user as degrees, then you can call `MathHelper.ToDegrees(angle)` at the very end.
> 6 votes

# Answer
I understand your problem to be this:

You want to know from your Actor where the mouse is so that you can point in roughly that direction. In particular, you are limited to 8 facings.

You can get most of where you want to go with determining the angle from point a to point b using Math.atan2, and then by changing to range from \[0..2\*PI) to \[0..8).

```
double theOctant=Math.Round(Math.Atan2(y2-y1,x2-x1)*4/Math.PI);

```

This will give you one of 8 values: -3,-2,-1,0,1,2,3,4, which will map to one of your eight directins.

0 is in the positive x direction, and increases going clockwise.

However, if you simply rotate your original x,y coordinate to the left by 90 degrees, like so:

```
double theOctant = Math.Round(Math.Atan2(-dx,dy) * 4 / Math.PI);

```

You wind up with a value of -4 for north, -3 for northeast, and so on, and simply adding 4 will give you 0..7, which is likely all you wanted in the first place:

```
double theOctant = Math.Round(Math.Atan2(-dx,dy) * 4 / Math.PI) + 4;

```

From here, you could cast to your enum if the values match up, and you are done.
> 0 votes

---
Tags: mathematics, vector, angles
---


title: How do I loop my animations seamlessly?

text:
# Question
Title: How do I loop my animations seamlessly?
I am trying a complete my method, which crops Maya-Animations (from Maya-Models) to specific ones using the SkinnedModelProcessor.

My only problem is, that after one animation-loop completes, the model stays in its last position for about 2-3 seconds until he catches up to the run-cycle again.

My goal is to get rid of that freeze time. I want to loop it seamlessly.

Here is what I wrote:

```
public AnimationClip getCurrentAnimation(string clipName, string cropName, float blendTime, int beginFrame, int endFrame, int totalFrames)
{
    //The new list which only has the specific keyframes
    List<Keyframe> region = new List<Keyframe>();

    //The original clip "Take 001" from Maya, which has every
    //animation in one timeline
    AnimationClip clip = _skinningData.AnimationClips[clipName];

    //The new duration of the cropped clip
    int duration = 0;

    //Since XNA makes 7502 frames out of 21, I have to
    //calc the region-keyframes to proper numbers
    if (endFrame == 0)
        endFrame = clip.Keyframes.Count;
    else
        endFrame = ((endFrame * clip.Keyframes.Count) / totalFrames);

        beginFrame = ((beginFrame * clip.Keyframes.Count) / totalFrames);

    //Start to sort out
        for (int i = beginFrame; i < endFrame; i += 1)
        {
           Keyframe k = clip.Keyframes[i];

           //Add duration of 16 (60fps) to overall-length
           //of animation, if this keyframe does some "real"
           //transformation, instead of being a static keyframe of XNA
           if (k.Time.Milliseconds > duration)
                duration += 16;

            k.Time = TimeSpan.FromMilliseconds(duration);
            region.Add(k);
         }

         AnimationClip cropped = new AnimationClip(cropName, TimeSpan.FromMilliseconds(duration), region);
         return cropped;
}

```

# Answer
> 5 votes
If you want seamless looping animations, create your animations so that the start of the loop is the same pose as the end of the loop. Then when one loop ends, you can simply start playing the second loop without needing to make any changes.

Alternatively, you can blend between the two animation poses. This is where you'll use your `blendTime` value. Spanning the amount of time defined in `blendTime`, use linear interpolation to blend between the last pose of the current animation and the first pose of the next animation.

---
Tags: xna, animation, maya
---


# Question
Title: Need to use trig to make a ship point in the right direction
I'm making a 2D spaceship-shooter game that moves in all directions, (i.e. ( -x, +x ),( -y, +y ) ).

I'm trying to make the spaceship face the direction of the movement according to a virtual joystick. The virtual joystick has it's x and y coordinates working correctly and they are normalized (ie. between -1 and +1) in both x and y.

I'm able to set the angle of the image I'm using by a call to

```
SetSpriteAngle(spriteNum, angle)

```

where the angle is in degrees. The problem I'm having is with the trigonometry involved.

I know from trig that calculating the angle is radius\*cos(x), and I could be wrong on that, so I tried this:

```
x = GetVirtualJoystickX(1)
y = GetVirtualJoystickY(1)
r = sqrt(x*x + y*y)

angle = r * cos(x)

SetSpriteAngle(1,angle)

```

Problem one is, there's no account for the Y direction, so I tried:

```
angle = r*cos(x) + r*sin(y)

```

Still a problem, just not working correctly, so I tried arcsine and arccosine:

```
angle = r*aCos(x) + r*aSin(y)

```

Now the image is just flipping in what seems like a random direction, and just in case it was calculating, instead of the total angle, perhaps it was the angle from the x intercept, so I tried:

```
if GetVirtualJoystickX(1) > 0 and GetVirtualJoystickY(1) > 0
    //angle = angle
elseif  GetVirtualJoystickX(1) < 0 and GetVirtualJoystickY(1) > 0
    angle = angle - 180
elseif  GetVirtualJoystickX(1) < 0 and GetVirtualJoystickY(1) > 0
    angle = angle - 270
elseif  GetVirtualJoystickX(1) > 0 and GetVirtualJoystickY(1) < 0
    angle = angle - 360
else
    angle = 0
endif

```

Now it's only flipping as if angle is close to 0 and moving occasionally in a certain 270 degree position I believe,

So I guess I'm going to have to admit that my trigonometry skills aren't what they used to be and ask you guys for some help, by the way sin(x) is where x is in degrees and sinr(x) is where x is in radians, so I might be missing it there too, frankly I'm just too confused to get any farther right now.

Thanks guys!

# Answer
> 0 votes
I found my own anwer using:

```
angle = atan2( GetVirtualDeviceY(1), GetVirtualDeviceX(1) );

```

with this, there's no need to do the if then statements for each quadrants.

# Answer
> 0 votes
I've had a huge problem with angles myself.
Now i'm not very good with math or trig, but I'll give you the code I use to calculate the angle between two Vector2's (Resulting angle is between the two vectors and the Y axis, I believe). Works pretty good.

```
internal static double calcAngle(Vector2 me, Vector2 foe)
{
    double angle;

    Vector2 direction = foe - me;
    direction.Normalize();
    float rotationInRadians = (float)Math.Atan2((double)direction.Y, (double)direction.X) + MathHelper.PiOver2;

    angle = MathHelper.ToDegrees(rotationInRadians);
    if (angle < 0)
    {
        angle = 360 + angle;
    }
    return angle;
}

```

As you can see, the *arc tan2* of the normalized *subtracted vector* of two vectors + *PiOver2* gives us an angle in radians.
The code below the aforementioned part transforms the angle to an angle in degrees (0-359 degrees, no negatives).

Hope this helps :)

*PS: You can use the angle to create a Z rotation on a matrix, then use the matrix to transform the ship's vector, thus making it "go" to the angle provided to the matrix. Ask me in the comment for the code if you want, i'll edit this answer.*

---
Tags: trigonometry
---


# Question
Title: A Simple Method To Create Island Map Mask
**I'm searching for a nice and easy way to generate a mask for an island map with C#.**

---

Basically I'm using with a random heightmap generated with perlin noise, where the terrain is NOT surrounded by water.

The next step would be to generate a mask, to ensure the corners and borders are just water.

Then I can just subtract the mask from the perlin noise image to get an island.

and playing around with the contrast..

and the gradient curve, I can get an island heightmap just like I want it..

(these are just examples of course)

so as you can see, the "edges" of the island are just cut off, which is not a big problem if the colour value is not too white, because I will just divide the grayscale into 4 layers (water, sand, grass and rock).

My question is, **how can I generate a good looking mask like in the second image?**

---

**UPDATE**

I've found this technique, it seems to be a nice starting point for me, but I'm not sure how exectly I can implement it to get the desired output. http://mrl.nyu.edu/~perlin/experiments/puff/

---

**UPDATE 2**

this is my final solution.

I've implemented the `makeMask()` function inside my normalisation loop like this:

```
        //normalisation
        for( int i = 0; i < width; i++ ) {
            for( int j = 0; j < height; j++ ) {
                perlinNoise[ i ][ j ] /= totalAmplitude;
                perlinNoise[ i ][ j ] = makeMask( width, height, i, j, perlinNoise[ i ][ j ] );
            }
        }

```

and this is the final function:

```
    public static float makeMask( int width, int height, int posX, int posY, float oldValue ) {
        int minVal = ( ( ( height + width ) / 2 ) / 100 * 2 );
        int maxVal = ( ( ( height + width ) / 2 ) / 100 * 10 );
        if( getDistanceToEdge( posX, posY, width, height ) <= minVal ) {
            return 0;
        } else if( getDistanceToEdge( posX, posY, width, height ) >= maxVal ) {
            return oldValue;
        } else {
            float factor = getFactor( getDistanceToEdge( posX, posY, width, height ), minVal, maxVal );
            return oldValue * factor;
        }
    }

    private static float getFactor( int val, int min, int max ) {
        int full = max - min;
        int part = val - min;
        float factor = (float)part / (float)full;
        return factor;
    }

    public static int getDistanceToEdge( int x, int y, int width, int height ) {
        int[] distances = new int[]{ y, x, ( width - x ), ( height - y ) };
        int min = distances[ 0 ];
        foreach( var val in distances ) {
            if( val < min ) {
                min = val;
            }
        }
        return min;
    }

```

this will give an output like in the image #3.

with a little bit of change in the code, you can get the originally wanted output like in image #2 -\>

```
    public static float makeMask( int width, int height, int posX, int posY, float oldValue ) {
        int minVal = ( ( ( height + width ) / 2 ) / 100 * 2 );
        int maxVal = ( ( ( height + width ) / 2 ) / 100 * 20 );
        if( getDistanceToEdge( posX, posY, width, height ) <= minVal ) {
            return 0;
        } else if( getDistanceToEdge( posX, posY, width, height ) >= maxVal ) {
            return 1;
        } else {
            float factor = getFactor( getDistanceToEdge( posX, posY, width, height ), minVal, maxVal );
            return ( oldValue + oldValue ) * factor;
        }
    }

```

# Answer
Generate regular noise with a bias for higher values towards the center. If you're wanting square-ish island shapes like you show in your example, I would use the distance to the closest edge as your factor.

With that factor, you can use something like the following when generating the mask noise:

```
maxDVal = (minIslandSolid - maxIslandSolid)

getMaskValueAt(x, y)
    d = distanceToNearestEdge(x,y)
    if(d < maxIslandSolid)
        return isSolid(NonSolidValue) //always non-solid for outside edges
    else if(d < minIslandSolid)
        //noisy edges
        return isSolid((1 - (d/maxDVal)) * noiseAt(x,y))
    else
        return isSolid(SolidValue) //always return solid for center of island

```

Where `distanceToNearestEdge` returns the distance to the nearest edge of the map from that position. And `isSolid` decides if a value between 0 and 1 is solid (whatever your cut off is). It's a very simple function, it might look like this:

isSolid(float value) return value \< solidCutOffValue

Where `solidCutOffValue` is whatever value you're using to decide between solid or not. It could be `.5` for even split, or `.75` for more solid or `.25` for less solid.

Finally, this little bit `(1 - (d/maxDVal)) * noiseAt(x,y)`. First, we get a factor between 0 and 1 with this:

`(1 - (d/maxDVal))`

Where `0` is on the outside edge and `1` is on the inside edge. This means our noise is more likely to be solid at the inside and non-solid at the outside. This is the factor we apply to the noise we get from `noiseAt(x,y)`.

Here is a more visual representation of what the values are, as the names might be misleading to the actual values:
> 12 votes

# Answer
If you're willing to spare some computational power for this, then you could use a similar technique to what the author of this blog did. (**NB:** If you wish to directly copy his code, it's in ActionScript). Basically, he generates quasi-random points (i.e. looks relatively uniform) and then uses these to create Voronoi polygons.

He then sets the outside polygons to water and iterates through the rest of the polygons, making them water **if a certain percentage of the adjacent polygons are water**. You're then left with a polygon mask roughly representing an island.

From this you can apply noise to the edges, resulting in something resembling this (the colours are from another, unrelated step):

You are then left with a (quite) realistic-looking island-shaped mask, which would serve your purposes. You could choose to use it as a mask for your Perlin noise, or you could then generate height values based on distance to the sea and add noise (although that seems unnecessary).
> 14 votes

# Answer
One very simple method is to create inverse radial or spherical gradient with center at the width / 2 and height /2. For masking you want to **subtract** the gradient from the noise rather than multiply it. This gives you more realistic looking shores with the drawback that the islands are not necessarily connected.

You can see the difference between subtracting and multiplying the noise with the gradient here: http://www.vfxpedia.com/index.php?title=Tips\_and\_Techniques/Natural\_Phenomena/Smoke

If you are unsure how to create radial gradient, you can use this as a start point:

```
    public static float[] CreateInverseRadialGradient(int size, float heightScale = 1)
    {
        float radius = size / 2;

        float[] heightMap = new float[size * size];

        for (int iy = 0; iy < size; iy++)
        {
            int stride = iy * size;
            for (int ix = 0; ix < size; ix++)
            {
                float centerToX = ix - radius;
                float centerToY = iy - radius;

                float distanceToCenter = (float)Math.Sqrt(centerToX * centerToX + centerToY * centerToY);
                heightMap[iy * size + ix] = distanceToCenter / radius * heightScale;
            }
        }

        return heightMap;
    }

```

Don't forget to scale your gradient to the same heightas your height map and you still need to factor in your water line somehow.

The problem with this method is that your height field will be centered around the center of the map. This method, however, should get you started with adding features and making your landscape more diverse as you can use **addition** to add features to your height map.
> 1 votes

# Answer
I second ollipekka's suggestion: what you want to do is subtract a suitable bias function from your heightmap, so that the edges are guaranteed to be underwater.

There are plenty of suitable bias functions, but one fairly simple one is:

```
f(x, y) = 1 / (x * (1-x) * y * (1-y)) - 16

```

where *x* and *y* are the coordinate values, scaled to lie between 0 and 1. This function takes the value 0 at the center of the map (at *x* = *y* = 0.5) and tends to infinity at the edges. Thus, subtracting it (scaled by a suitable constant factor) from your height map ensures that the height values will also tend to minus infinity near the map edges. The just pick any arbitrary height you want and call it the sea level.

As ollipekka notes, this approach will not guarantee that the island will be contiguous. However, scaling the bias function by a fairly small scale factor should make it mostly flat in the middle area of the map (thus not affecting your terrain much), with a significant bias appearing only near the edges. Thus, doing so should give you a squarish, mostly contiguous island with, at most, possible a few tiny sub-islands near the edges.

Of course, if you don't mind the possibility of disconnected terrain, a somewhat larger scaling factor should give you more water and a more natural-looking island shape. Adjusting the sea level and/or the scale of your original heightmap can also be used to vary the size and shape of the resulting island(s).
> 1 votes

---
Tags: c#, procedural-generation, perlin-noise, masking
---


# Question
Title: LibGdx: How do I combine 2 GestureListener objects from 2 seperate classes into 1 GestureDetector
I'm trying to make 2 separate classes, 1 a VirtualJoystick class and 1 a VirtualButton class. I want to implement a GestureListener class in each, it just seems like good code to do so, but when I go to my main program, how do I add both GestureListener classes?

Here's some pseudocode that I'm thinking of:

```
VirtualJoystick vjs = new VirtualJoystick(x, y, width, height, bgImage, fgImage);
VirtualButton vb    = new VirtualButton(x,  y,  width, height, upImage, dnImage);

GestureDetector joyGestureDetector = new GestureDetector( vjs.getDetector() );
GestureDetector btnGestureDetector = new GestureDetector(  vb.getDetector() );

// Here's what I don't know how to do
GestureDetector combinedGestureDetector = ?

Gdx.input.setInputProcessor(combinedGestureDetector);

```

but as you can see, I'm stuck on how to combine the two, if there's a better way let me know, I'm just trying to get my code to "think through well" and be atomically contained in classes.

# Answer
The quick and dirty way to fix this is to use InputMultiplexer. This allows you to pass those gesture events to both detectors.

```
VirtualJoystick vjs = new VirtualJoystick(x, y, width, height, bgImage, fgImage);
VirtualButton vb    = new VirtualButton(x,  y,  width, height, upImage, dnImage);

GestureDetector joyGestureDetector = new GestureDetector( vjs.getDetector() );
GestureDetector btnGestureDetector = new GestureDetector(  vb.getDetector() );
//Note: you need return false in your event handlers like touchDown(...),
//so that the event gets passed to both detectors you added to the multiplexer.
InputMultiplexer multiplexer= new InputMultiplexer(joyGestureDetector,btnGestureDetector);

Gdx.input.setInputProcessor(multiplexer);

```
> 1 votes

---
Tags: java, libgdx, input
---


title: Cave generation with Perlin worms

text:
# Question
Title: Cave generation with Perlin worms
I'm currently trying to generate a Minecraft like voxel terrain with 3D Simplex Noise and also want to implement caves.

I found the method of Perlin Worms in this thread, which generates really nice results. However, I have no clue on how to generate it on a chunk by chunk basis. Is this possible or are there any alternatives that produce a similar worm like cave on a chunk by chunk basis?

Edit: This is the problem which I don't know how to solve.

Edit2: This is the result from combining 2D Ridged Multifractal Noise with a Simplex Noise heightmap. Still needs some tweaking, but this is pretty much the result I wanted. Thanks to Byte56.

# Answer
Most perlin noise algorithms will allow you to retrieve the noise value at any given location, with something like `noise(x,y,z)`. This makes it fairly trivial to generate noise on a chunk by chunk basis. All you need to do is pass the global position, instead of the chunk position.

```
for(int i = 0; i < CHUNKMAX_X; i++)
    for(int j = 0; j < CHUNKMAX_Y; j++)
        for(int k = 0; k < CHUNKMAX_Z; k++)
            if(isSolid(perlinNoise.get(chunkPosition.x + i,
                                         chunkPosition.y + j,
                                         chunkPosition.z + k))
                thisChunk[i,j,k] = new Voxel(solid);
            else
                thisChunk[i,j,k] = new Voxel(air);

```

So you can see, we're generating terrain for the chunk, by iterating over the chunk bounds, and checking to see if that global position is solid or not. This is likely the same methodology you're using to generate the terrain in general.

`perlinNoise.get` takes a global position and returns its density. Where `isSolid` would just be a simple test to see if the voxel is "dense enough" to qualify for solid.

`perlinNoise.get` can be more complex than just a simple noise algorithm. You can have checks based on the depth of the voxel in your world. For example, if the voxel is below what you've decided is "absolute base ground level" then it can use the perlin worms algorithm to return a density, if it's above the absolute base, it can use a normal density function to give you more varied terrain. I would recommend some blending between the two however.

Combining different Perlin noise functions is just something you have to play with and see what works. It's best to set up your environment so that you can just change some values and hot-swap the terrain without needing to reload your game. Happy experimenting.
> 6 votes

# Answer
I think this is how it works in Minecraft. Each worm has a maximum length (let's call it `M`). The heads of each worm are calculated based on the chunk position. When you render each chunk, you have to check all chunks within an `M` radius, and follow all of their worms. It's not ideal in terms of performance, but it does work.
> 5 votes

---
Tags: terrain, minecraft-modding, voxels, perlin-noise
---