# Question
Title: Is Java viable for serious game development?
I have scoured the internet, but there are not very many resources for Java game development, not nearly as many as C++. In fact, most engines are written in C++. I tried to play a game made with jMonkeyEngine, but the game was terribly slow, to the point where my computer froze. I had no other Java applications running, and nothing too resource intensive. In contrast, my computer can play most modern 3D games with ease. If I continue to learn and improve Java now, and it turns out that later I am required to learn C++, making the switch might be difficult.

Is Java an acceptable language for serious game development? By serious, I mean high quality graphics, without much lag on modern computers. I also want to consider making games for consoles.

# Answer
Yes it is, check this list for a proof. Those are some games made with Java using The Lightweight Java Game Library (LWJGL). It is a low-level framework, which provides OpenGL for high quality graphics and OpenAL for sounds. It also provides input API. With these you can quite easily get started to serious game development in Java.

I am currently writing my second 3D game as a hobby project in Java, and I just love it. In the past I used to write my games with C++, but after switching to Java there is no going back. Supporting multiple operating systems with Java can be very easy, for example my previous Java game, which I developed in Windows for a year, worked in Linux right away and in OS X with only one bug without any need to compile anything on those platforms.

On the other hand, with Java you have couple of problems.

1. Garbage collector. As others have stated, non-deterministic memory management is a problem, and you need to code that in mind.
2. Lack of 3rd party libraries. Most of the available libraries do not support Java. On the other hand you always have the option to call these native libraries from Java also, but it's more work to do so. There are also Java ports or ready-made wrappers available for popular libraries, for example I'm using JBullet - Java port of Bullet Physics Library. On the other hand Java has a huge class library built-in, which reduces the need for third party libraries that are not game related. The lack of libraries has not been a problem for me, but I can imagine that it can be for others.
3. Java is not supported by popular game consoles and there is no easy switch to those from Java as far as I know. On the other hand Android, which is a popular mobile platform, uses some form of Java. This is an option also, but don't except the same Java code to work both on a PC and Android device.
4. Smaller community. Most game programmers use C++ and in my experience often dislike Java. Don't expect to get as much help from others. Don't expect to get a job in game development without C++ skills.
> 54 votes

# Answer
Not really. Here's the thing- firstly, there's very little in terms of existing libraries for Java compared to the *virtually everything* that is for C++.

Secondly, Java as a language simply doesn't lend itself well to game development- I mean, for example, if you're dealing with GPU buffers then Java does not provide a language feature which will aid you in ensuring they are correctly locked and unlocked or disposed of, which C++ does. Plus, there's the performance problem- and the GC is non-deterministic, which is super-bad for a game.

I have never observed any non-indie game which spent significant time in a language that was not compiled to native code prior to execution, and even the indie games which do so are a rarity. So my belief right now is that it simply cannot be done.

> Also, if I continue to learn and improve Java now, and it turns out that later I am required to learn C++, will making the switch be difficult?

Yes, absolutely it will. Java and C++ are *vastly* different, despite their superficial syntactic similarities. Java experience counts for virtually nothing when learning C++.

Gameplay over graphics *is* a viable choice, and you can see it in the success of games like Terarria and Minecraft. But if you intend on creating srs graphics, then it's not going to be doable in Java.
> 42 votes

# Answer
> So, I am really serious about game development, is Java still a viable choice? I have tried multiple times to learn C++, but I don't really like the language. I don't really know why, but usually, whenever I try to learn, I can never grasp the topics.

If your reason for choosing Java is that you couldn't understand C++, your Java programs aren't going to be fast enough for high quality graphics. Using a higher level language should be because it makes you more productive, not because you couldn't understannd the lower level language.

I don't think it's an entirely bad idea to write a game in Java, especially if the game is simple, but you're immediately going to run into performance issues in Java if you're using it as a crutch.

> So, in short, can Java be taken serious, for serious game development. This includes heavy graphics, fast game play without lag, and possibly, and easy switch to consoles?

1. Heavy Graphics: Possible, but you're going to be doing the same thing in Java/LWJGL as you are in C++/GL: writing bytes to GPU buffers and/or using the deprecated display lists like Minecraft does. If you don't understand the memory management, you're not going to do this correctly either.
2. Fast game play without lag: Not an easy task in any language, and you're more likely to shoot yourself in the foot either way without putting thought into it.
3. No, Java is not going to be available on consoles.
> 25 votes

# Answer
An experienced programmer will generally know many programming languages - learning extra programming languages isn't too hard once you know one well. However I would strongly recommend that C++ shouldn't be your first language, and probably not the second one either.

That's because C++ gets a lot of its efficiency from not doing any significant runtime error checking. For example accessing an element off the end of an array in Java will always throw an exception telling the programmer exactly what's wrong. In C++ you may get lucky and it will crash immediately, but very frequently it will silently trash some other data and the error won't show up till much later on.

I'd suggest you stick with Java for now (or switch to C# if you prefer that). That will let you get things done quicker than using C++, and performance on a PC shouldn't be an issue.

Think about learning C++ after you've completed a few projects in safer languages. C++ is what you'll need for most professional game development jobs.

Note that with the exception of C#/XNA getting a game you wrote onto a console at a minimum requires you to set up a company, with an office, and have a large budget available for development hardware and other expenses.
> 15 votes

# Answer
**Disclaimer:** This doesn't exactly answer your question. However, I have attempted to (briefly) mention some points that may be of interest to you.

The reason that you see so much about C++ is because C++ is still the industry standard -- the most common language for consoles, etc.

Java is not frequently used. Minecraft is a pretty popular game that made it big with Java; but it's not that great graphically. Spiral Knights is not bad -- also made in Java, with significant graphics.

If you like Java, C# is very similar in syntax, with the advantage that it can interop with C++ -- so low-level stuff can be done in C++ if necessary. Unity can use C# for scripting, and XNA is an excellent choice.

Again, Java is not widely used. If you like the style and syntax, I think you'll find C# to be a very similar, very pleasant coding experience.

I hope your dreams make it, it's a lot of fun along the way :)
> 9 votes

# Answer
Look dude, the simple answer to "Is Java **viable** for game dev" is an obvious yes. You can use any programming language to make games. That doesn't mean you **should**.

Probably the very things that turns you off from C++ (low level memory management, no garbage collector, having to pay attention to pointers, structs as arrays etc) **are the very things that you should learn if you want to exploit a computer's resources most efficiently**. Your games will run best if you are exploiting the computer's resources most efficiently.

Java does some things (such as array bounds checking) that just make it run slower. In this optimized Java Perlin noise example code, the author commented "(array access is a lot slower than member access)". This kind of thing is pretty counter intuitive coming from a C++ background. But in Java, such things are.

I say stop dodging the bullet, learn C++, and use it.
> 4 votes

# Answer
This doesn't answer your question; the graphics and console issues seem to be something you very much need to consider. Also GC affects on performance. But what I write about:

If you are writing large, complex, OO programs, you will write them 5 times faster in Java than C++. Also, maintenance will be vastly easier. I switched, (admittedly for non-game software), and my productivity skyrocketted. C#, another good alternative, is harder to learn than Java because there's a lot more of it. When you know it, you can write code even faster than in Java; it offers you a lot of tricks. However, I find those tricks can make maintenance difficult. And then there's Java doc, which helps with the Sun libraries *and* your own old code. C# has nothing quite like it.

I did a big hairy game in Java and found the language perfect, but my graphics were elementary and it wasn't a shooter where a tenth of a second was an eternity to the players. Also, I expect to add a lot on to it later, whereas I think most people just go and write a brand new game.
> 3 votes

# Answer
**You should do it in the language you know best until you can afford a formal education (Bachelor's of Science?) in Computer Science, emphasizing game design.** You could possibly use your game to get a scholarship, especially if you can say "I did this without any formal training in Java"

Modern JVMs, even the one from Oracle, have many, many features to address the concerns people have brought up here. You can use different garbage collectors to get more deterministic garbage collector behavior. I don't have extensive experience with the 3D libraries - only a little with Java3D - but nobody here seems to have complained about them. Escape analysis now allows lock elision and much faster/negligible allocation of very short-lived objects.

The problem is, whether you choose Java of C++, you'll have to learn how to properly use concurrency and have a good understanding of memory management. After all, you can just as easily screw up with `malloc` as you can with `new`. I don't know what the tools are like for C++, but the profiling tools for Java are fairly easy to use, free, and integrated with the IDE. You can use them to track down performance problems and *learn*.
> 1 votes

---
Tags: java, game-industry
---


# Question
Title: Making various shapes equally difficult to tap
I'm developing a game where the player quickly has to tap/click on various shapes such as squares, circles, triangles, stars and so on. I'm now struggling with the following task: I'm searching for a normalized size for each shape, so that every shape is equally difficult to hit. E.g. given a circle with a radius `r`, how do I find the length `l` of the corresponding square?

At first glance I thought: Easy. Just make all shapes share the same area `A`. So, in the example above, `l = sqrt(pi)`. http://en.wikipedia.org/wiki/Squaring\_the\_circle

But on second thought, this does not seem to be the best metric. Imagine a star with many long, thin, pointy arms or a very long but thin line. Even if they have the same area as a circle or square, they are still more difficult to hit.

So, what might be a better approach? Maybe something involving the "form factor" (circumference squared divided by area `C²/A`)?

# Answer
> 7 votes
Sounds like play testing is going to be the best strategy here.

You can use your idea of making all the shapes the same area to start with. Then add a "shape factor" to modify the size if need be. You can use this shape factor to apply to every object of a specific shape. Once you've tested enough, you'll have shape factors you can use for each shape.

---

Alternatively (and more difficult to implement), use a circle to scale them all. Take a circle of radius X, and ensure that each generated shape has the same surface area inside the circle.

For example, below, the star is scaled so that its surface area within the circle is the same surface area as the square has inside the circle:

(Likely not actually scaled correctly since I just did it in paint)

# Answer
> 1 votes
Sounds like Fitts's Law.

Fitts's law is a very good approximation for the speed of humans hitting targets by moving along a straight line.

> where:
>
> * T is the average time taken to complete the movement. (Traditionally, researchers have used the symbol MT for this, to mean movement time.)
> * a represents the start/stop time of the device (intercept) and
> * b stands for the inherent speed of the device (slope). These constants can be determined experimentally by fitting a straight line to measured data.
> * D is the distance from the starting point to the center of the target. (Traditionally, researchers have used the symbol A for this, to mean the amplitude of the movement.)
> * W is the width of the target measured along the axis of motion. W can also be thought of as the allowed error tolerance in the final position, since the final point of the motion must fall within ±W⁄2 of the target's center.

You can treat the line from *target 1* to the next *target 2* as your straight line. Then calculate an average participant's `a` and `b` constants by experiment. This allows easily calculating an appropriate `W` (width) for every instance of the problem.

---
Tags: user-interface
---


title: How do I make a ship fire shots?

text:
# Question
Title: How do I make a ship fire shots?
I am making a Galaga-like game. How can I make the ship fire gunshots? What logic do I need to make it work? I am using libgdx to develop the game. I have gotten the ship and an enemy on stage, but I have ran out of ideas for making the ship fire.

# Answer
> 3 votes
So you have managed to **spawn** a Ship and an Enemy?

If so, creating a shot is simple. Simply spawn another Object like the Ship and Enemy, that (for starters) moves forward very fast and gets destroyed on impact.

The program does not care if it is a Ship, or a bullet. All it wants is to move stuff around and do logic.

---
Tags: libgdx
---


title: Is Minecraft's source code available?

text:
# Question
Title: Is Minecraft's source code available?
I recall Mojang stating they would release the source code of Minecraft sooner or later, but searching both on google and on Minecraft sites I wasn't about to find it.

So... is it available somewhere? With what license?

PS: not interested in sources decompiled from the binaries, only in genuinely officially released sources.

# Answer
No.

Notch said at some point that he plans to release the sources once the game is no longer selling, but that was WAY before it got this big.

And yes, it's still selling.
> 7 votes

# Answer
I know there's an already accepted answer and it's not quite on the spot - but I also came here via Google and I was looking to learn and thought others might, too.

There are other open-source Minecraft clones (and InfiniMiner which is what Minecraft is based off, too).

I'd suggest anyone who is looking to study up on it looks at these:
> 7 votes

---
Tags: minecraft-modding
---


# Question
Title: Synchronizing input, update and rendering threads
How do you synchronise the *input-handling*, *state-updating* and *rendering* threads?

If a sprite position is modified due to input, the wrong position of the sprite might be drawn to the screen if the render thread draws the sprite before the update thread finishes its collision resolution routine.

How can this be done?

(The only solution I can think of would be to store input events as they are created and consume them in the update/render threads.)

# Answer
Your question is very general and I haven't faced that problem yet. But I have a basic idea how this can work. In your example, the input thread need to communicate with the state thread and the state thread need to communicate with the rendering thread.

There are two concepts coming to my mind here. First, you could make use of double buffers. For example, the state thread provides its results in the front buffer. While the renderer reads them, it continues working and stores the results in the back buffer. Each time new results are available, the buffers are switched so that the newest state is read always.

Another concept that might be favorable is a queue. For example, the input thread captures the input events and simple adds the actions to a thread safe queue. The state thread can fetch them anytime and they are removed from the queue after that.

In contrast to this way of using a double buffer, the queue ensure that all input events arrive.

My personal guess is that, as you already mentioned, the lack of synchronization wouldn't be too important. Since input, state and renderer have a higher frequency then the human eye can notice (hopefully) there might be no need for synchronization. But as I already said I haven't faced this problem yet so I cannot assure that totally.
> 0 votes

---
Tags: rendering, input, game-loop, multithreading
---


# Question
Title: opengles display human face in iphone and animate it?
I need to make a human 2D face to 3D face. I used this link to load an ".obj" file and map the textures. This example is only for cube and pyramid. I loaded a human face ".obj" file.

This loads the .obj file and can get the human face properly as below.

But my problem here is I need to display different human faces without changing the ".obj" file. just by texture mapping.

But the texture is not getting mapped properly, as the obj file is of different model. I just tried changing the ".png" file which is used as texture and the below is the result, where the texture is mapped but not exactly what I expected, as shown below.

The below are my few questions on it :

1) I need to load texture on same model( with same .obj file ) with different images. Is it possible in opengles?

2) If the solution for above problem is "shape matching", how can I do it with opengles?

3) And finally a basic question, I need to display the image in large area, how to make the display area bigger?

# Answer
The texture map needs to be explicitly created for the model.

More accurately, the model includes a UV coordinate for each vertex that maps each vertex to specific points in the texture map. Generally this is done by creating a model and "unwrapping" it, which generates a template texture map file that an artist can paint to create the final model. This painting is generally done after the model geometry is all finished, as small tweaks to the model geometry will often necessitate drastically different unwraps (even when controlled by an artist and not done auto-magically by tools).

This UV mapping means that a texel mapping to the center of the left eye may be at texture position 20,20 for one model, but texture position 400,50 for another. If you open the face texture, you'll see bits of face all over, and a lot of stretching, with odd "cuts" in certain places. Those places varies for each model based on how UVs were unwrapped for its specific geometry. The texture map has to match these UV coordinates or you get the garbled effect you're seeing.

Short version is that if your .PNG is not made for the .OBJ you're using, it won't work. You can't grab some random face texture and some random head model and expect things to look right.
> 1 votes

---
Tags: textures, ios, cocos2d-iphone, opengl-es, objective-c
---


title: 2D Motocross physics

text:
# Question
Title: 2D Motocross physics
I'm looking into making a 2D motocross bike game with plausible physics.

It should look like this:

For a first try, I've created only the player (a motocross driver) and the map (consisting of **only straight lines**; no curves, to keep it simple).

How should collisions between the motocross bike and the track affect the bike's position and velocity? The bike should *rotate* if only one of the wheels touches the ground and *speed up* if the back wheel touches the ground. Pretty standard bike game stuff.

How do I achieve this behaviour?

# Answer
> 2 votes
I would first focus on the general motorcycle physics.

But because there are a lot of forces at work in the real world and you don't want to simulate them all, I would go for some basic forces like gravity, friction and torque.

You can use the torque to calculate the motion of the wheels of the motorcycle. And you can use the friction to let the wheels of the motorcycle have grip on the ground and make them stop spinning when you don't have a external force on your motorcycle (gravity, thrust etc.)

Also when you want to have ragdoll like behavior for your driver you can use inverse kinematics.

I hope you can do something with this information!

---
Tags: physics, terrain, collision-resolution
---


# Question
Title: Networking Questions: Serialization and Frequent Small Packets or Fewer Large Packets
I'm working with a socket server and I'm trying to decide how to update all of the clients.

I'm currently sending few packets with entire objects serialized in JSON. In most cases this adds a lot of overheard in the form of unneeded data. This to me is a no brainer, get rid of the serialization and send only what is needed.

Lets say I have four server-side AIs. Should I send all four of the AIs in one giant update, therefore serializing only the needed data or should I send each one in a separate update?

# Answer
> 12 votes
When you send small messages, you have to be aware of the protocol overhead:

Imagine you are sending a 10 byte message.

A TCP header is 24 bytes, an UDP header is 8 bytes. Assuming you use UDP, you have 18 bytes in total.

But you also have the IP header, which is at least an additional 20 bytes in IPv4 or 40 bytes in IPv6. That's 38 bytes in total when you use IPv4.

And then you also have the ethernet frame around all that, which is (usually) another 42 bytes. So you are at 80 bytes. That's 7 times as much protocol overhead as the data you were sending.

As you see, sending small data messages is not very bandwidth-efficient because there is a fix-cost of 70 bytes of protocol overhead for each message.

`to visualize this better, seventy bytes is as much data as this string`

But delaying small messages just so you can send more at the same time is often not a good idea either, because this will make the game feel more laggy.

There is no golden hammer solution to finding the ideal compromise for this. But all data which is available at the same time should be sent in one message instead of separating it into multiple. There is nothing to gain and a lot to lose by adding unnecessary fragmentation on the application level.

(Image source: http://en.wikipedia.org/wiki/File:UDP\_encapsulation.svg)

# Answer
> 0 votes
Generally speaking, if the game is fairly large or sends a lot of updates you should pack your packets small. However, if your game is only small and just something to play around with and scalability isn't a huge concern - just do what works.

---
Tags: networking, multiplayer, serialization
---


# Question
Title: Moving AutoParallaxBackground's ParallaxEntity in X and Y direction
Currently I can move AutoParallaxBackground's "ParallaxEntity" in **one axis**. Like:

```
final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 12);
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, 0, resourcesManager.gameBackgroundRegion, vbom)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-3.0f, new Sprite(0, 300, resourcesManager.gameCloudFarRegion, vbom)));

```

This will make the "gameCloudFarRegion" move left to right.

I want to move something from **Top to bottom or bottom to top**, I mean **Y axis**.

How can it be done?

# Answer
A user on the forums has implemented a custom class for doing this. From their post:

> Should be quite flexible, you can tile in just x (as the current parallax background, for side scrollers etc), just y (to make a top down shooter etc), or x & y (repeating starfields for free shooters etc).You can also place individual non repeating items in the background parallax, e.g a distant planet, the castle off in the hills etc.
> 2 votes

---
Tags: andengine
---


# Question
Title: Algorithm to see if two voxels are interconnected
I'm looking for a good algorithms for the following problem: Given a 3D grid of voxels (which may be either empty or filled), if I pick two non-adjacent voxels, I want to know if they are connected to each other by other voxels.

For example (to illustrate the situation in 2D), where # is a filled square:

```
  1 2 3
a # # #
b # #
c # # #

```

If I pick a3 and c3, I want to determine as quickly as possible if they they are connected; if there is a path between a3 and c3 through filled pixels. (The real situation is in a 3D voxel grid, of course.)

I've looked at floodfill algorithms and path finding algorithms, but I'm not sure which to choose. Both do unneccesary work: Flood fill tries to fill all voxels, but this is not needed. Path-finding algorithms are usually concerned with finding the shortest path, which is also not necessary. I only need to know if there *is* a path.

What algorithm should I be using?

Edit: based on the comments, I think should add the following: the content of the voxels are not known in advance, and also, the algorithm is needed to detect if removal (emptying) of a voxel would cause the group of voxels to break into two or more smaller groups.

# Answer
A\* would work just fine. Path finding is what you want, finding the shortest path is just as fast (or faster) than finding any path at all. In this situation A\* is likely the most suitable given you have a start and end point. this means you have the added heuristic to speed up the search.

With A\* typically the first path you find is the shortest, so it's not doing extra work after it's already found a path.

For some optimizations, check out my answer here.
> 12 votes

# Answer
If you're prepared to do some pre-processing and eat the storage cost, then partitioning voxels into connected groups at build time gives an obvious answer to 'is there a path at all'. There is a path between two voxels if they're in the same group. The problem with that obviously is that you have to store group information somewhere, and that depends on your data layout. If you're storing a simple list, you can just break that into multiple lists, one for each spatially connected group. If you're organising in some kind of BVH, then you could probably get some reasonably good efficiencies if you can say "all voxels in this node and below belong to group X".

Alternatively, you could do some spatial pre-partioning and store some smaller set of 'hub' voxels for each connected group. Then you can path-find from your source and target voxels to their nearest hub voxel, which should be a much shorter / cheaper to calculate path. If you can find a path from a voxel to a hub voxel, then the voxel is part of the hub voxel's group. With smart selection of those hub voxels, you can minimise the number of path traversals. E.g. a sphere might have just one hub voxel in its centre, but a long thin group might have a hub voxel every X voxels along its length. If your source and target voxels are at either end of the length, they only have to go at most X voxels to find a hub, and even though there might be a huge number of voxels between the start and end of the length, the pathfinding involved would be relatively short.

It all depends on just how pathological your voxel groups are: if you expect a huge number of smallish disconnected groups, the increase in storage cost is going to massively outweigh the performance hit of just pathfinding. If you expect relatively few connected groups but of odd topologies, then naive pathfinding might be hugely expensive and the storage cost and minimal pathfinding is a much cheaper option.
> 9 votes

# Answer
I'm not very familiar with voxels, but I would imagine that you could get quite good performance from using a best-first search algorithm such as A\*. The problem with using A\* in this instance is that the heuristic one would normally use is designed to prioritise finding the shortest path and not just 'any path' as quickly as possible.

You may have some luck using an alternate heuristic which expands fewer nodes such as

f(p) = g(p) + w(p) * h(p)

where w \>= 1. you decrease the value of 'w' the closer you get to the goal, thereby giving a higher priority to the path cost 'g' the closer you get to the voxel you're looking for.

I hope this helps!
> 4 votes

---
Tags: 3d, algorithm, path-finding, voxels
---


# Question
Title: Can you use well known buildings in your game?
Is it legal to reference a real city in your game and use the same architecture of well known shops and buildings?

For example, I'm sure you can't create an exact 3D model of McDonalds, put it in your game, and sell it. However, is it possible to use the same architecture, but different name? and even use the same colors, just as long as the name and logos are not used? Or would there be the possibility of getting in trouble for creating something in the "likeness".

# Answer
First, a disclaimer: I'm a lawyer who practices in California, but this post is not intended as legal advice. "Is it legal" questions are inherently not a good idea for the stack exchange format. Different jurisdictions have different laws, and in many jurisdictions, offering legal advice absent a license constitutes unauthorized practice of law (*i.e.*, it's a crime). Moreover, you should not rely on advice you find online to determine whether some conduct is legal or illegal. Finally, circumstances vary. Whether your use of architecture is lawful or unlawful may depend on specifics that are not provided by your question.

So the real answer is: **consult with a competent lawyer in your jurisdiction**.

Having said that, by way of background, I can tell you that there have been lawsuits related to allegedly unauthorized uses. My favorite example is E.S.S. Entertainment 20002, Inc. v. Rockstar Videos, Inc., et al., 547 F.3d 1095 (9th Cir. 2008), which involved Grand Theft Auto: San Andreas, and the allegation that the game infringed on an actual strip club:

> ESS Entertainment 2000, Inc. ("ESS"), operates a strip club, which features females dancing nude, on the eastern edge of downtown Los Angeles under the name Play Pen Gentlemen's Club ("Play Pen"). ESS claims that Rockstar's depiction of an East Los Santos strip club called the Pig Pen infringes its trademark and trade dress associated with the Play Pen.

Rockstar prevailed in that lawsuit on first amendment and fair use grounds, but that does not mean you would, nor does it mean that the matter was cheap or trivial for Rockstar to defend.

If you're considering using a real building or, for example, parodying it by tweaking the name PlayPen to PigPen, you may someday find yourself answering questions at a deposition like this:

> "Q Okay. Did anything humorous about pigs in any way influence your artistic creation of the PIGPEN? A I can't remember. . . . Q As you sit here today can you think of anything funny about pigs that may have inspired or influenced your artistic rendition of the PIGPEN?"
> 18 votes

# Answer
I think you basically have answered your own question by pointing out that you couldn't copy a McDonalds. That is, if the answer is "Yes" for a McDonalds, it is "Possibly" for other buildings.

Unless I suppose you are modelling old or historical landmarks (Ancient Rome, The Alamo, Brandenburg Gate, etc.)
> 1 votes

# Answer
Provided they're both publicly owned and reasonably old, I can't see a reason not to. If for example, you copy the Statue of Liberty, Eiffel tower or something, I don't know who's going to sue you.

On the other hand, I would probably steer clear of Apple, Inc. latest HQ :)
> 0 votes

---
Tags: legal, licensing
---


# Question
Title: how to add fog to a model instantiated in Xna?
I work on a small XNA games. I generate a large map type voxel. a floor of 1000 cubic long by 1000 cubes wide. This is why I use the method "MODEL instancing" with hardware instancing to generate a large number of identical model ..

My problem is how to add fog to the cubic field? I know it is very easy to utiler fog with the class **Microsoft.Xna.Framework.Graphics "BasicEffect"**. unfortunately i can not use this class because of the instancing model ...

I use **Microsoft.Xna.Framework.Graphics "Effect"** and does not contain a property "FogEnable, FogColor etc ..."

Do you have a solution to bring me to allow me to draw a fog on my models instantiated?

Thank you so much.

Here is my code that draws models

```
foreach (ModelMesh mesh in model.Meshes)
        {

            foreach (ModelMeshPart meshPart in mesh.MeshParts)
            {
                // Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer.
                Game.GraphicsDevice.SetVertexBuffers(
                    new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0),
                    new VertexBufferBinding(instanceVertexBuffer, 0, 1)
                );

                Game.GraphicsDevice.Indices = meshPart.IndexBuffer;

                // Set up the instance rendering effect.
                Effect effect = meshPart.Effect;
                //effect.CurrentTechnique = effect.Techniques["HardwareInstancing"];
                effect.Parameters["World"].SetValue(modelBones[mesh.ParentBone.Index]);
                effect.Parameters["View"].SetValue(view);
                effect.Parameters["Projection"].SetValue(projection);
                effect.Parameters["Texture"].SetValue(texture);

                // Draw all the instance copies in a single call.
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    Game.GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0,
                                                           meshPart.NumVertices, meshPart.StartIndex,
                                                           meshPart.PrimitiveCount, instances.Length);
                }
            }

        }

```

My error if i use the technique (effect..Parameters\["FogColor"\]):

# Answer
You need to add fog as parameters in a gpu shader file.

For example, set various parameters in your code:

```
float FOGNEAR = 250.0f;
float FOGFAR = 300.0f;

effect.Parameters["FogColor"].SetValue(Color.SkyBlue.ToVector4());
effect.Parameters["FogNear"].SetValue(FOGNEAR);
effect.Parameters["FogFar"].SetValue(FOGFAR);

```

And then, in the effect shader file that is chosen, use them such as:

```
float FogNear;
float FogFar;
float4 FogColor;

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
   float fog = saturate((input.Distance - FogNear) / (FogNear-FogFar));

   return lerp(FogColor, color, fog);
}

```
> 2 votes

---
Tags: c#, xna, graphic-effects, effects
---


title: Reusable skill class structure

text:
# Question
Title: Reusable skill class structure
Pretty new to the whole game development scene, but I have experience in other branches of programming. Anyway, I was wondering what methods are used to implement a skill structure. I imagine a skill in itself would a class. I'm using actionscript 3 for this project btw.

```
public class Skill
{
    public var power:int;
    public var delay:int;
    public var cooldown:int;

    public function Skill(user:Mob, target:Mob)
    {

    }
}

```

Each skill would extend the Skill class and add it's own functionality.

```
public class Tackle extends Skill
{
    public function Tackle(user:Mob, target:Mob)
    {
        super(user, target);
        executeAttack();
    }

    private function executeAttack():void
    {
        //multiply user.strength with power etc
        //play attack animation
    }
}

```

This where I get stuck. How do I termine which mobs has which skills? And which skill will they later be able to retrieve (by reaching a certain level etc). How does the player actually execute the skill and how is it determine if it hits. It's all very new to me so I have no idea where to begin. Any links would also be appreciated. Thanks in advance.

# Answer
> 5 votes
There's a lot of different directions you could go with this. What kind of game are you making, and what does type Mob represent? It sounds like you need to separate your concerns more.

> How do I termine which mobs has which skills?

If each skill is its own class, and each skill extends the Skill class, then that leads me to think you should have a `Vector.<Skill>` field in the Mob class.

Assuming you need to instantiate the skill for purposes of state management (like cooldowns and other things), then this Vector. would contain objects which are-a Skill. To search for a specific skill, it could be useful to give Skill a property called Name which is overridden by subclasses of Skill. Then you can search through a mob's Vector. looking at the name of each skill until you find the one you're looking for.

A more robust solution would be to analyze your gameplay such that you don't even need to subclass Skill, and you could create entirely new skills by setting the properties of the skill class accordingly.

> And which skill will they later be able to retrieve (by reaching a certain level etc).

This is a larger architecture question.

> How does the player actually execute the skill

Presumably, the player is a Mob, and there's a keyboard mapping such that Attack gets called. Why do you have a separate function, executeAttack defined in the Tackle class?

> and how is it determine if it hits.

This is something you need to decide. Read up on collision detection for checking if a point intersects a region on the screen, or find a D&D rulebook and look at how the Difficult Class system works.

---

It sounds like you're biting off more than you can chew. Try breaking this game down into something simpler. Build individual aspects of it into smaller games, then as you learn more you will be able to assemble the bits and pieces you've learned on the way into something bigger.

# Answer
> 2 votes
Language and words are extremely important in programming. And your "situation" is the result of their misuse in abstracting classes. You need to determine which of the two are happening here. Reading 1: Mobs have Skills i.e. TacklingSkill etc. and when a target approaches it, the mob uses a Skill of choice? Reading 2: Actions like Tackle take place between two Mobs when they interact, collide etc.

Solution: I think you know what you want. Just rethink the names and your structure will derive itself from it. Use simple, straightforward and descriptive words. Do not mix concepts (i.e. actions with what creates them or what they result in or what is required for them).

# Answer
> 1 votes
There should be two layers - logical and presentational. Power etc. belongs to the logical level while the animation belongs to the presentation layer.

`Skill` constructor doesn't need `mob` and `target`. Remove them. Also, skill shouldn't be executed on creation.

There are probablu should be different types of skills - permanent passive skills ( masteries), temporary spells (bonus auras), active non-targeted spells (Frost Nova), active directional spells (Fireball), active targeted spells (Mana Drain). Each skill type has a slightly different invokation methods.

There is also a hard architectural problem of **Classes** / **Types**, **Objects** / **Instances** (and type objects). `DefenceAura` is a *type* of skill and has `Duration`, but the `CastedDefenceAura` is an *instance* of skill and has `TimeLeft`. There can also be `PlayerSkill` classes which the player acquired and can level. Normally OOP languages only have two "type layers" - classes and objects. But for skills we need slightly more. I designed a system where there are three types of spell classes: `Spell` (the one described in the rule book) which can be given to a player (at certain skill leven) as a `PlayerSpell` (has level and cooldown) and `CastedSpell` (flying in some direction)

The skill system may look something like this:

**Skills**

```
 public class Skill {
     public var Name:string;
     public var MaxLevel:int;

     public function GiveToPlayer(player:Mob, level:int) : PlayerSkill {}
 }

 public class PermanentPassiveSkill extends Skill { } //Regeneration

 public class SkillWithCooldown {
     public var Cooldown:float;
 }

 public class DurationalSkill extends SkillWithCooldown { //Chilling Armor
     public var Duration:float;
 }

 public class SelfTargetedSkill extends SkillWithCooldown { } //Heal, Frost Nova

 public class DirectionalSkill extends SkillWithCooldown { } //Acid spray, normal and ranged physical attacks

 public class PointedSkill extends SkillWithCooldown { } //Firewall, Meteor

 public class TargetedSkill extends SkillWithCooldown { } //Mana drain

```

**Player skills**

```
 public class PlayerSkill {
     public var Skill:Skill;
     public var Player:Mob;
     public var Level:int;
 }

 public class PlayerSkillWithCooldown {
     public var CooldownLeft:float;
 }

 public class SelfTargetedPlayerSkill extends PlayerSkillWithCooldown {
     public function Activate() : CastedSkill { }
 }

 public class DurationalPlayerSkill extends SelfTargetedPlayerSkill {
     public function Activate() : CastedDurationalSkill { }
 }

 public class DirectionalPlayerSkill extends PlayerSkillWithCooldown  {
     public function Activate(direction:Vector) : CastedDirectionalSkill { }
 }

 public class PointedPlayerSkill extends PlayerSkillWithCooldown  {
     public function Activate(target:Point) : CastedPointedSkill { }
 }

 public class TargetedPlayerSkill extends PlayerSkillWithCooldown  {
     public function Activate(target:Mob) : CastedTargetedSkill { }
 }

```

**Casted skills**

```
 public class CastedSkill {
     public var PlayerSkill:PlayerSkill;
 }

 public class CastedDurationalSkill extends CastedSkill {
     public var TimeLeft:float;
 }

 public class CastedDirectionalSkill extends CastedSkill {
     public var Direction:Vector;
 }

 public class CastedPointedSkill extends CastedSkill {
     public var Target:Point;
 }

 public class CastedTargetedSkill extends CastedSkill {
     public var Target:Mob;
 }

```

**Animations**

```
 public class PlayerSkillAnimation { //Casting/attack animation
     public var PlayerSkill:PlayerSkill;
 }

 public class CastedSkillAnimation { //Projectiles animation
     public var CastedSkill:CastedSkill;
 }

```

**Concrete skill implementations**

```
 public class Fireball extends DirectionalSkill {
    public var DamagePerLevel:float;

    public function GiveToPlayer(player:Mob, level:int) : PlayerFireball {
        return new PlayerFireball(self, player, DamagePerLevel * level)
    }
 }

 public class PlayerFireball extends DirectionalPlayerSkill {
    public var Damage:float;

    public function PlayerFireball(skill:Skill, player:Mob, level:int) {
        super(skill, player)
    }

    public function Activate(direction:Vector) : CastedFireball {
        return new CastedFireball(this, direction);
    }
 }

 public class CastedFireball extends CastedDirectionalSkill { }

```

It may look very complicated, but such skill system can bring clarity to the chaos of the skill code.

---
Tags: actionscript-3, design-patterns, rpg
---


# Question
Title: Is it legal to pack LibGdx libraries in my jar file? And to obfuscate them?
I'm using LibGDX and deploying a runnable jar file, using the Eclipse feature, with libraries extracted into it. There are also .so files and .dlls inside.

1. Is it legal to do so? I didn't find anything about deploying to a single jar file.
2. If 1 is legal, if I obfuscate the jar file, maybe with ProGuard, will it be still legal?

# Answer
> 7 votes
Obviously not a lawyer, so this isn't legal advice, but my personal interpretation is:

The code is licensed under Apache License, Version 2.0. If you read the **Redistribution** section:

> You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form...

So, yes, you can package it with your jar file. And I would argue that obfuscating the code is modifying it. However, one of the conditions of redistribution is:

> If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file...

You need to keep all the notices intact. So don't obfuscate those away :).

# Answer
> 2 votes
According to the Google Code page, the license is attribution + share-alike. I quote (emphasis mine):

> Share Alike — If you **alter, transform,** or build upon this work, **you may distribute the resulting work** *only under the same or similar license* to this one.

That means "yes."

---
Tags: java, libgdx, encryption, deployment
---


title: Voxel terrain engine

text:
# Question
Title: Voxel terrain engine
Is there some voxel frameworks or extensions for game engines like Unity? I really need a system to dynamically generate voxel ruinable terrains.

# Answer
> 5 votes
There's a good source for that here

Currently the free ones (with source) are:

---
Tags: unity, terrain, voxels
---


# Question
Title: How to scroll background image-Android App
Basically, I have a main menu, and I would like the background image to scroll (parallax I believe is the term? Like the Angry Bird's title screen background).

However, I'm used to just having a variable iterate (x++) and setting that as the x value so the image scrolls.

So is there any way to confer variables and such between xml and my java files so I can use iteration? Or can I skirt this completely somehow?

# Answer
You can check this example of mine which scrolls the background. But I would not recommended that you have widgets or views on top of a SurfaceView animations. AngryBirds I believe draws its own graphics interface as all good games do.

https://stackoverflow.com/questions/4938822/how-can-i-use-the-animation-framework-inside-the-canvas/4946893#4946893
> 3 votes

---
Tags: android
---


# Question
Title: Where to show user shot's power on touch screen?
I want to show user shot power in standart way (the more user holds finger on the screen the stronger is shot)

Where is the best place to show this icon on touch screen(when I use mouse it's better to show it at the mouse position):

* static at screen side or top
* at finger position (how to handle clicking at screen bounds? what offset to use to avoid hiding behind finger?)

Will be glad to see any good examples you liked.

# Answer
> 7 votes
There are pros and cons to both, but the decision is ultimately yours. You'll have to decide based on the style of your game and the type of game.

* **Static position**: Always in the same place, predictable. This means the user will always know where the indicator will be and allows them to avoid covering it up on their own. Kind of boring and requires some kind of constant HUD.
* **Dynamic position**: Potentially more intuitive, and feels more interactive. Easily allows for a HUD-less display. Potential of being covered up by fingers.

There are changes you can make to both to offset the pros and cons. For example you can make the static indicator pop down when activated, but always pop down to the same spot. Or you can make the dynamic indicator large enough that it couldn't be covered up.

**User interfaces benefit greatly from play testing.** It's often hard to tell how people will want to use the application until they start using it. For these types of play testing, give it to people and leave the room, so they can test it without you watching over them. Try giving some people instructions and let others try to figure it out on their own. Have a few different versions of the UI implemented for them to test.

# Answer
> 3 votes
As Byte56 said, the decision is yours. But my personal opinion is that an floating HUD game is better. I think something like this: is better if you don't need the extra space around the user's finger that's occupied by the GUI. Then you can make it adapt depending on some variables, like it becoming smaller when an enemy is hit, ...

# Answer
> 2 votes
Going to throw another thought out there; how about a ripple circle outwards? Have a circle s that its orgin begins at the point that user touches. Have the radius of the circle expand outwards to indicate that it is "growing" and gaining more power. This will allow the user to see their power gauge immediately as their eyes are already following the mouse - and it gives immediate feedback upon inspection.

Keeping the gauge off to the side is an option if real estate is direly limited but otherwise it keeps the users fixed without having to move around. If aiming is involved, this is especially important; you wouldn't want the user to have to divert his/her attention between two different places.

---
Tags: ios, gui, touch, hud, usability
---


# Question
Title: Quit the application when clicking cancel button of Alert View in C#
Can someone guide me as to how can I make an application quit when you press the cancel button of an Alert View in C# code?

Thanks

---

I forgot to add that I am trying to quit application on clicking ok button on alert view which I am developing on Unity platform.

# Answer
> 1 votes
You're not supposed to programmatically quit iOS apps.

http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/mobilehig/UEBestPractices/UEBestPractices.html#//apple\_ref/doc/uid/TP40006556-CH20-SW27

> Don’t Quit Programmatically
>
> Never quit an iOS app programmatically because people tend to interpret this as a crash. However, if external circumstances prevent your app from functioning as intended, you need to tell your users about the situation and explain what they can do about it. Depending on how severe the app malfunction is, you have two choices.
>
> Display an attractive screen that describes the problem and suggests a correction. A screen provides feedback that reassures users that there’s nothing wrong with your app. It puts users in control, letting them decide whether they want to take corrective action and continue using your app or press the Home button and open a different app
>
> If only some of your app's features are unavailable, display either a screen or an alert when people use the feature. Display the alert only when people try to access the feature that isn’t functioning.

more: https://stackoverflow.com/questions/12242319/is-it-possible-to-quit-ios-app-after-we-do-some-checks

That being said, you can call `exit(0)` but it's highly not recommended. https://stackoverflow.com/questions/1707685/how-to-quit-an-iphone-app-nicely

---
Tags: c#, unity, objective-c, unityscript
---


title: Creating a frozen bubble clone

text:
# Question
Title: Creating a frozen bubble clone
This photo illustrates the environment: https://i.stack.imgur.com/uLPNp.png

I'll shoot the cannon, it'll bounce off the wall and it's SUPPOSED to stick to the bubble. It does at pretty much every other angle. The problem is always reproduced here, when hit off the wall into those bubbles. It also exists in other cases, but I'm not sure what triggers it.

What actually happens: The ball will sometimes set to the wrong cell, and my "dropping" code will detect it as a loner and drop it off the stage.

\**There are many implementations of "Frozen Bubble" on the web, but I can't for the life of me find a good explanation as to how the algorithm for the "Bubble Sticking" works. \**

I see this: http://www.wikiflashed.com/wiki/BubbleBobble https://frozenbubblexna.svn.codeplex.com/svn/FrozenBubble/

But I can't figure out the algorithims... could anyone explain possibly the general idea behind getting the balls to stick?

Code in question:

```
    //Counstruct our bounding rectangle for use
    var nX = currentBall.x + ballvX * gameTime;
    var nY = currentBall.y - ballvY * gameTime;
    var movingRect = new BoundingRectangle(nX, nY, 32, 32);
    var able = false;

    //Iterate over the cells and draw our bubbles
    for (var x = 0; x < 8; x++) {
        for (var y = 0; y < 12; y++) {
            //Get the bubble at this layout
            var bubble = bubbleLayout[x][y];
            var rowHeight = 27;

            //If this slot isn't empty, draw
            if (bubble != null) {
                var bx = 0, by = 0;

                if (y % 2 == 0) {

                    bx = x * 32 + 270;
                    by = y * 32 + 45;

                } else {
                    bx = x * 32 + 270 + 16;
                    by = y * 32 + 45;
                }

                //Check
                var targetBox = new BoundingRectangle(bx, by, 32, 32);
                if (targetBox.intersects(movingRect)) {
                    able = true;

                }
            }

        }

    }

   cellY = Math.round((currentBall.y - 45) / 32);

if (cellY % 2 == 0)
    cellX = Math.round((currentBall.x - 270) / 32);
else
    cellX = Math.round((currentBall.x - 270 - 16) / 32);

```

Any ideas are very much welcome.

Things I've tried:

Flooring and Ceiling values Changing the wall bounce to a lower value Slowing down the ball

None of these seem to affect it. Is there something in my math I'm not getting?

# Answer
Model the playing field as a hexagon grid. Each bubble is actually a hexagon shape for its connections:

Each flat side is where a bubble can connect. When a bubble touches another bubble, snap the bubble in motion to the nearest hexagon grid location.

Finding the nearest is essentially a picking operation, so the math for finding where the bubble will stick is the same. You can find some great answers for that here.
> 6 votes

---
Tags: javascript, html5, physics
---


# Question
Title: OpenGL ES 2.0: Vertex and Fragment Shader for 2D with Transparency
Could I knindly ask for correct examples of **OpenGL ES 2.0 Vertex and Fragment shader** for displaying 2D textured sprites **with transparency**?

I have fairly simple shaders that display textured polygon pairs but transparency is not applied despite:

* texture map contains transparency information
* Blending is enabled: glEnable(GL\_BLEND); glEnable(GL\_DEPTH\_TEST); glBlendFunc(GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA);

*My Vertex Shader:*

```
uniform mat4 uOrthoProjection;
uniform vec3 Translation;

attribute vec4 Position;
attribute vec2 TextureCoord;

varying vec2 TextureCoordOut;

void main()
{
    gl_Position = uOrthoProjection * (Position + vec4(Translation, 0));
    TextureCoordOut = TextureCoord;
}

```

*My Fragment Shader:*

```
varying mediump vec2 TextureCoordOut;
uniform sampler2D Sampler;

void main()
{
    gl_FragColor = texture2D(Sampler, TextureCoordOut);
}

```

# Answer
> 3 votes
Bunkai (I expect that Bunkai is your first name),

turn off the depthBufer. Do you use depth (different Z)? If not why depthBuffer? It is for 3D or layered 2D.

Transparent objects are rendered **always** after opaque objects. Do you use this order?

It must be one of this, i'm sure.

# Answer
> 4 votes
Are you sure that your texture has an alpha channel. Add this line in your fragment shader:

```
gl_FragColor = vec4(texture2D(Sampler, TextureCoordOut).xyz, 0.5);

```

You should see some half transparency texture.

Ps: Your result color will be darker, because it is a mix with color in backbuffer\*0.5 and the gl\_FragColor\*0.5. Blending is done after the fragment in the OGLES 2.0 pipeline.

Your equation is:

```
ResultColor.r = glFragColor.r * glFragColor.a + ColorInBuffer.r * (1.-glFragColor.a)
ResultColor.g = glFragColor.g * glFragColor.a + ColorInBuffer.g * (1.-glFragColor.a)
ResultColor.b = glFragColor.b * glFragColor.a + ColorInBuffer.b * (1.-glFragColor.a)

```

# Answer
> 0 votes
enable blending glEnable(GL\_BLEND); glBlendFunc(GL\_SRC\_ALPHA,GL\_ONE\_MINUS\_SRC\_ALPHA); also,check if texture has alpha channel opaque, rendered front to back transparent, back to front

---
Tags: opengl, opengl-es, graphics-programming
---


title: Geometry shader worldviewprojection

text:
# Question
Title: Geometry shader worldviewprojection
I'm writing a simple geometry shader to create 3D "primitives" in place of a single point. I am performing all of the world-view-projection conversions within the geometry shader after creating the triangle strips to form the 3D primitive. Unfortunately, it seems to be creating the triangles in projection space, and giving me incorrect results. The following pictures demonstrate this problem. Any advice on how to work around this problem?

As can be seen here, the second top face seems to be rendered as if it was pulled off the top and splayed out.

Here is the geometry shader I am using, and a set of coordinates I use to generate these faces

```
static float3 cube_coords[8] =
{

float3(1, -1, 1),
float3(-1, -1, 1),
float3(1, 1, 1),
float3(-1, 1, 1),

float3(1, 1, 1),
float3(-1, 1, 1),
float3(1, 1, -1),
float3(-1, 1, -1),

};

[maxvertexcount(8)]
void GSMain(point GSInput input[1], inout TriangleStream< GSOutput > output)
{
GSOutput p;

for(unsigned int j = 0; j < 2; j++)
{
    for(unsigned int i = 0; i < 4; i++)
    {
        p.Pos = input[0].Pos;
        p.Pos += float4(cube_coords[i + (4*j)],1.0);
        p.Pos = mul(p.Pos, worldViewProjection);
        p.Color = input[0].Color;
        p.Light = input[0].Light;
        p.Norm = normals[j];
        output.Append(p);
    }
    output.RestartStrip();
}
}

```

# Answer
I have encountered the answer to this question myself. I had simply made a mix-up involving column major vs row major matrices, and the order in which i was multiplying them against my position within the geometry shader.
> 1 votes

# Answer
Before going into geometry shader loop, coordinates you provide are not cube coordinates if it's what you are trying to achieve.

Your code:

```
float3(1, -1, 1),
float3(-1, -1, 1),
float3(1, 1, 1),
float3(-1, 1, 1),

float3(1, 1, 1),
float3(-1, 1, 1),
float3(1, 1, -1),
float3(-1, 1, -1),

```

5th point covers 3rd point and 6th point covers 4th point.

Edit: Sorry just realized I misunderstood the question.

Edit2: Not sure it's what causes the problem but vertex positions leaving the geometry shader must be transformed to homogeneous clip space. This is how it's usually done: (pseudocode)

```
struct VStoGS
{
   float3 position : POSITION;
   //other stuff
};

struct GStoPS
{
   float4 positionH : SV_POSITION; //for homogeneous clip space transform
   float3 positionW : POSITION; //for world space transform
   //other stuff
};

```

And in geometry shader:

```
foreachvertex
{
   gsOutput[i].positionW = mul(float4(vertex[i].pos, 1.0f), world).xyz;
   gsOutput[i].positionH = mul(float4(vertex[i].pos, 1.0f, worldViewProj);
   //other stuff
}

```

Edit3: positionW is only needed for extra stuff in PS so that's not it.
> 0 votes

---
Tags: c++, shaders, directx11
---


title: OpenGL ES multiple indices

text:
# Question
Title: OpenGL ES multiple indices
I need suggestions for the best method of acheiving what I am trying to do:

-Using either OpenGL ES 1.x or 2.x

I need to pass a bunch of vertices to the GPU. Each one has 3 attributes: Position, Color, and Texture coords.

The vertices form quads, which share vertices. The shared vertices have both position and color attributes in common, but texcoords are not shared because each quad is textured with a 'tile' from a texture atlas.

I already know that it is not possible to use separate indices for a glDrawElements() call, so does that mean I can only use indexing for individual quads(specify 4 unique vertices per quad)? .. or is there any better solution?

# Answer
> 1 votes
If you have a lot of quads (with shared vertices), but each quad needs its own texcoords, you can't use shared vertices, but each quad has to be defined separately.

It's better to use interleaved arrays in each case, because you have stored all attributes for one vertex consecutively in memory. So if you are trying to read for example vertex position, also some surrounding data from memory (in your case color and texcoords) are send to cache. If you have a lot of data, it's more efficient.

And you don't have to use glDrawElements in this case, you can just use glDrawArrays (you don't have to pass indices, if they are just sequence of increasing numbers).

I also hope, you are using VBOs (data are stored in GPU memory instead of system memory).

# Answer
> 0 votes
Use `glDrawElements` and pass `GL_TRIANGLE_FAN` (4 indexes per quad).

You can use an uniform to get to a specific region in the texture, so your quads share the same texcoords but map to a certain area using the uniform variable.

---
Tags: opengl, 3d, iphone, android, shaders
---


# Question
Title: Game development lesson plan (9-12yr old)
I have been invited to help a couple of students make a video game. I would be working with 2-3 students aged 9-12 yrs.

The time frame is 10 x 2hr classes over 10 weeks, with plenty of preparation time on to get some assets ready.

Does any one know of an existing lesson plan for this kind of thing that I could use and contribute to; or ideas as to what the kids could achieve in this time frame? Type of game? 3d/2d? Should they make models, be given models and do programming? Do you have any experience with what kids this age respond well to?

I have a preference towards open source frameworks, but could be convinced to use a free commercial framework if you think there is enough benefit.

# Answer
Your question about whether they should make models or be given models and focus on programming is really a basic question about what subject matter you're teaching. There's no reason you couldn't spend 10 weeks (or more) on just model creation. If it's a course in making a video game, I would keep the asset-creation to a minimum, which means go with a 2D rather than a 3D game. There's some great art assets available at opengameart, including very professional and flexible artwork created for the Liberated Pixel Cup.

My suggestion would be to start with a platformer. Ten weeks ought to be enough time to get a basic one working. I'd imagine you'd start with the idea of the game loop, then rendering a sprite to the screen, then moving the sprite in basic ways, then more sophisticated ways of moving the sprite (jumping! shooting), then creating and loading a map, working with a camera, generating enemies, basic collision detection. I wouldn't spend more than a single lesson on the asset creation, except to show them some basic tools to edit images, then provide the opengameart materials and if they wanted to tweak those they could do so. If you had time in the course you might get to some fancier terrain features, moving platforms, ladders, platforms you can jump "up" through, etc., but you may not get there in ten weeks.
> 2 votes

# Answer
What are you exactly trying to teach these children?

Are you trying to teach them basic programming or are you trying to just make a game so they understand core mechanics and breaking problems down?

If the first I would either start on XNA teaching C# and breaking down into sudocode for them as it's pretty easy to get something displaying quickly.

If the latter, why not introduce them to Construct 2 or Gamemaker.Both are free for what you seem to want. You can find tutorials everywhere to get a game up within hours.
> 0 votes

---
Tags: education
---


title: Dynamic model scaling

text:
# Question
Title: Dynamic model scaling
Imagine a (3D) game like Railroad Tycoon 3. Player selects a rail track, clicks LMB and drags the mouse to the end position. During this drag, the rail track model scales and adopts to the landscape, so user sees the resulting track in dynamic.

The question: how this can be done? A brief idea/links/sketches will be enough. I just don't know how to start (I'm novice game developer). If it is matter, I use Unity as a game engine.

Thanks in advance.

# Answer
As RobCurr states, simplest way to do this is to make sure the landscape mesh "matches" the track tile size, so that you don't get tracks that jutt above a hill or go through a suddenly ending slope.

What you can do in Unity is make a script that tells you the point on the landscape where the mouse cursors "is". I say "is" because obviouslly a 2d moving mouse cursor doesn't really intersect a 3d landscape. What you actually wanna do is create a ray cast from the camera, through the cursor and onto the landscape, and use the point where that ray goes through the landscape as the point where the mouse cursor "is" on the landscape.

Look up Raycast and this post here

Then you need to script up the behaviour of the track tile when the user drags his mouse "across" the landscape: how the track tile needs to be rotated, should it be straight or curved (if the player changes direction after already laying down some tracks), etc. Make sure you have a good grasp of prefabs and how to instantiate them for this part.
> 1 votes

---
Tags: unity, models
---


title: Cant import Sun openGL

text:
# Question
Title: Cant import Sun openGL
I've been working with JOGL and I've ran into a problem. The problem is when I try to import `import com.sun.opengl.*;` on Eclipse, Eclipse doesn't recognize it. Does anyone know where this library is? Did I miss a step during installation? I'm working with the latest build.

Here are the included libraries:

* gluegen-rt-natives-windows-i586.jar - JOGL/lib
* gluegen-rt - JOGL/lib
* gluegen.jar - JOGL/lib
* jogl-all-natives-windows-i586.jar - JOGL/lib
* jogl-all.jar - JOGL/lib

This is within my JOGL project folder:

* gluegen-rt.dll

# Answer
> 1 votes
Found what I was looking for. A separate jar file located here:

http://www.java2s.com/Code/Jar/j/Downloadjogl20jar.htm

# Answer
> 3 votes
SUN/Oracle are not maintaining JOGL 1 since 2009. http://labb.zafena.se/?p=656 \- The JogAmp community now maintains JOGL 2 and Java3D.

Casses found under com.sun.opengl.\* are now found under com.jogamp.opengl.\* in JogAmp JOGL 2.

If you want to use JOGL that support both mobile, tablets and desktops then its recommended to migrate your code to JOGL 2 that is well maintained and got better support for all new shader based GPU OpenGL profiles. http://jogamp.org/jogl/doc/Overview-OpenGL-Evolution-And-JOGL.html

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


# Question
Title: My 2d Shader in XNA falls apart the second I put it into Farseer
I wrote a simple light shader that I tested in a simple 2d spaceship shooter and it worked fine. Once I imported it into my friend's farseer project with rotatable shapes, it doesn't seem to work well with the shapes moving around and rotating. Could someone help me fix it and maybe plugging in good values to get it to work?

code sample:

```
/*LIGHT DIRECTION VARIABLES*/
float2 lightposition;
float2 textureposition;
float textureheight;
float texturewidth;
float lightwidth;
float lightheight;
float2 screensize;
float2 lightsize;
float rotationrads; /*assumed rotation is in radians*/
float lightgradient; /*a number from 0 to N for how intense the shift in light per pixel from source is */
float texgradient; /*a number from 0 to N for how intense the shift in light per pixel from 0,0 in the texture is */
float lightintensity; /*0-1 for 100% rgb, over 1 for modified whiteness*/

float4 LightDirection(float2 Tex: TEXCOORD0) : COLOR0
{
    float4 Color = tex2D(TextureSampler, Tex);

    float2 abszero;
    abszero.x = 0;
    abszero.y = 0;
    float sizescreen;
    float2 finaldistance;
    float2 percentdistance;
    float length;

    sizescreen = abs(distance(abszero, screensize));

        float2 NewTex;
        NewTex.x = Tex.x * cos(rotationrads) - Tex.y * sin(rotationrads);
        NewTex.y = Tex.x * sin(rotationrads) + Tex.y * cos(rotationrads);
        if(textureposition.x >= lightposition.x && textureposition.x <= lightposition.x + lightwidth)
        {
            finaldistance.x = 0;
        }
        else if(lightposition.x + lightwidth > NewTex.x)
        {
            finaldistance.x = textureposition.x - (texturewidth * ((1.0 - NewTex.x) * texgradient));
        }
        else
        {
            finaldistance.x = textureposition.x + (texturewidth * (NewTex.x * texgradient));
        }

        if(textureposition.y >= lightposition.x && textureposition.y <= lightposition.y + lightheight)
        {
            finaldistance.y = 0;
        }
        else if(lightposition.y + lightheight > textureposition.y)
        {
            finaldistance.y = textureposition.y - (textureheight * ((1.0 -NewTex.y) * texgradient));
        }
        else
        {
            finaldistance.y = textureposition.y + (textureheight * (NewTex.y * texgradient));
        }

    length = abs(distance(lightposition, finaldistance));
    length = (length/sizescreen);

    Color.r = (Color.r * lightintensity) -(Color.r * (length * lightgradient));
    Color.g = (Color.g * lightintensity)  - (Color.g * (length * lightgradient));
    Color.b = (Color.b * lightintensity)  - (Color.b * (length * lightgradient));

    return Color;
        }
        technique LightOnly
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 LightDirection();
    }
}

```

# Answer
A bit of guessing here because I have no clue what a shader "falling apart" means. Most likely Farseer altered the renderstate at some point.

See Shawn Hargreaves Blog for tons of information about render states.

But you probably want to add the before before your drawing code. This should reset everything back to the XNA defaults.

```
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

```
> 0 votes

---
Tags: xna, 2d, directx, shaders, farseer-physics-engine
---


title: LWJGL Eclipse Resource Deployment

text:
# Question
Title: LWJGL Eclipse Resource Deployment
I'm still experimenting with some OpenGL in LWJGL, and as I get to know more and more about OpenGL, I start to do more complicated things like multi texturing, shadowmapping and more. Now, right now I'm using the src folder (src/res) for my resources, and use src/resourcename in my code. When I export it, this won't work on another location as the relative path is ofcourse incorrect. What would be the best way of deploying your game with all the resources in one file? Maybe put the files in the jar?

I would like to hear from a few people how they store and deploy their project with resources, thanks!

# Answer
> 5 votes
Don't put the resources in your source folder. Instead do something like this:

* Project root
    + src
    + res
        - images
        - shaders
        - sounds

There are two common ways to load resources in Java applications.

# 1. File system

In the code you can load the resources from file system with relative path "res/images/filename.png". While developing, use Project root as the working directory. When deploying the project, just copy the res folder to the same folder where the executables are located. You can also omit the res folder if you want to or call it something else.

# 2. JAR resources

Add the res folder to your classpath. You can then load the resources using ClassLoader.getResourceAsStream("images/filename.png"). Note the missing res folder from the path. When deploying, add the content of res folder to your .jar file.

It's also possible to put local resources next to the source files even deep in the package hierarchy. These resources can be loaded with Class.getResourceAsStream("relativepath"), where path to the resource is relative to the package of the class calling this method. I would **not** recommend this approach for game assets.

---

If the resources are considered as read-only after deployment, I would recommend the second approach. If on the other hand the player is allowed to modify or add resources to the game, the first approach works better.

---
Tags: opengl, java, lwjgl, architecture
---


title: Semi Transparent Background in Scene

text:
# Question
Title: Semi Transparent Background in Scene
In my game I want to create game over scene which is semi transparent so game scene become partially visible.

Game over scene contain several button that are not transparent but I need only background become semi transparent.

I have used scene management structure so people have to consider this also. I have already tried following things \*) set background enable method to true \*) create large rectangle up to screen size and set alpha.

But unfortunately about things not work for me. So please provide me some useful information about my problem.

# Answer
you can use simple dialog using layout file. in this you can set transparent background.

i find one temporary solution for your que. if you don't use background on scene then below code help you. in this you can set background as sprite.

```
Scene yourGameOverScene = new Scene();
yourGameOverScene.setBackgroundEnabled(false);
Sprite spriteBG = new Sprite(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT,
                    dBgRegion);
spriteBG.setBlendFunction(GL10.GL_SRC_ALPHA,
                    GL10.GL_ONE_MINUS_SRC_ALPHA);
spriteBG.setAlpha(0.1f);
yourGameOverScene.attachChild(spriteBG);
YourActivity.this.getEngine().setScene(yourGameOverScene);

```
> 1 votes

# Answer
Is there any reason you cannot use a semi-transparent .png as your background image, then layer whatever else you need on top of that?
> -1 votes

---
Tags: sprites, flash, cocos2d, andengine
---


# Question
Title: Determining if removal of a voxel will break up a group
I have the following situation: I have a 3d grid of voxels (on/off, the max size is probably 128x128x128). I know in advance that inside the grid, all the voxels that are turned on are interconnected, forming a single group.

Now I need to determine: when I remove a voxel (turn it off), will it break up the group?

My initial idea was to look at neighbors of the voxel that is removed and determine if they are still interconnected trough other voxels (see my other question: Algorithm to see if two voxels are interconnected). But there might be better/other ways to do this.

So what would be a good way to determine if removal of a voxel will break up the group it was part of?

# Answer
I covered this somewhat in my other comment, but I think here you're thinking about external / internal classification. By removing a voxel, you are changing the voxels around it into 'edge' voxels (if they weren't already). This should boil down into 3 actual cases (symmetry gets you the rest of them) - in the example below the numbers are the group IDs, the - is the voxel being removed

```
11      2
1-     1-     1-2

```
* The first case is trivial - it's a corner, but the voxels above and to the left remain fully connected through the other voxel.
* The second case: it's a corner and the removed voxel has disconnected the above and left voxels that were previously connected
* The third case: it's a line, and the removed voxel has disconnected the left and right voxels previously connected.

If you identify that the 2nd or 3rd cases have happened, you need to do some path-finding to see if 1 and 2 are still connected through their other adjacent voxels.

You can get some efficiency here though. If a voxel is entirely internal to a group (i.e. all 8 of its neighbours are part of the same group), then it can be discounted. Why? It's a topology thing. Imagine the 2D case - there are only two possibilities. Either there is a single edge which, regardless of how it twists and turns, still forms a ring of voxels. Or, there are two rings, one containing one voxel, and one containing the other. E.g.:

```
 xxx xxx
 x x-x x
 xxx xxx

```

or

```
 xxxxxxx
 x     x
 xxx xxx
   x-x
 xxx xxx

```

That should extend to 3D as well, except instead of a boundary ring, you'd have a boundary surface. So when you are trying to determine whether the two recently disconnected voxels are still connected, you can exclude all the internal voxels from your traversal, because by definition if a voxel is connected to any one of the boundary voxels of a group, it is also connected to all the internal voxels in that group.

It's sort of the reverse effect of the hub voxels I talked about in my answer to the other question - you don't have to find your way from every voxel to every other voxel, you only have to find your way to the **interesting** voxels.
> 4 votes

# Answer
If you're using A\*, you can utilize it here.

Starting with a list of the voxels that were connected to the removed voxel. Begin with the first in the list, use A\* to find a path to the second in the list. If a path exists, find a path from the second to the third, third to fourth and so on.

Most of those searches will be very fast, because the voxels will be right next to each other. If there's any path that fails, it means a discontinuity has been created.

This should be pretty easy to implement if you already have the A\* functionality implemented.
> 3 votes

---
Tags: algorithm, voxels
---


title: Struggling to get set up with JOGL2.0

text:
# Question
Title: Struggling to get set up with JOGL2.0
I did have JOGL1.1 set up and working, but I soon discovered that it did not support the latest OpenGL, so I started work on upgrading to JOGL2.0 it's not gone too well.

Firstly, is it worth me trying to get JOGL to work, or should I just move over to LWJGL? I am fairly comfortable with OpenGL (via C++) and from what I did get working with JOGL1.1, I seem to be OK adapting to it.

Assuming that I stick with JOGL, am I foolish for trying to use JOGL2.0? From what I can gather, JOGL2.0 is still in beta, but I am willing to go with it as I want to make use of the latest OpenGL I can.

I have been using the Eclipse IDE and have set up a user library for JOGL, here is a screen shot of the configuration and I have added this user library to my own Eclipse project. the system variable %JOGL\_HOME% points to "C:\Users\edacosh\Downloads\JOGL2.0" so that should work fine.

Now, the problem I actually having, when I try to run my code, on the line

```
GLProfile glp = GLProfile.getDefault();

```

The code stops with the following message...

```
Exception in thread "main" java.lang.NoClassDefFoundError: com/jogamp/common/jvm/JVMUtil
    at javax.media.opengl.GLProfile.<clinit>(GLProfile.java:1145)
    at DiCE.DiCE.<init>(DiCE.java:33)
    at App.<init>(App.java:17)
    at App.main(App.java:12)
Caused by: java.lang.ClassNotFoundException: com.jogamp.common.jvm.JVMUtil
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 4 more

```

I have also set my project to ensure that it is using jre6 along with jdk6, as I was having some issues.

# Answer
> 1 votes
That error simply means that the JVM couldn't find the com.jogamp.common.jvm.JVMUtil class. You are most likely missing a JAR in your build path configuration.

As for LWJGL vs JOGL, that's up to you (and is entirely opinion, so not a good fit for this site); perhaps this and this will help you. Notice that JOGL 2.0 has been out for over a year, perhaps several years.

# Answer
> 0 votes
In order to fix the "Exception in thread "main" java.lang.NoClassDefFoundError: com/jogamp/common/jvm/JVMUtil"

You need to add the gluegen-rt.jar and jogl-all.jar to the classpath for both java and javac, the two jars are provided by JogAmp JOGL.

You may want to read the JogAmp Wiki that include setup instructions on how to do this:

http://jogamp.org/wiki/index.php/Setting\_up\_a\_JogAmp\_project\_in\_your\_favorite\_IDE

http://jogamp.org/wiki/index.php/Setting\_up\_a\_JogAmp\_project\_in\_your\_favorite\_IDE#Compile\_and\_run\_your\_project\_from\_the\_command\_line

# Answer
> 0 votes
I had really good luck using this: http://www3.ntu.edu.sg/home/ehchua/programming/opengl/JOGL2.0.html

---
Tags: opengl, java, jogl, eclipse
---


# Question
Title: Moving a sprite towards an x and y coordinate
Given a sprite with an x and y coordinate, how would I move it toward another sprite with an x and y coordinate?

I've already made it face towards the other sprite, and I've made it move towards the other sprite, however because I'm using `sin` and `cos` it's circling the player and slowly moving in on them. Here's the method:

```
Enemy.prototype.update = function(playerX, playerY) {
    // Rotate us to face the player
    this.rotation = Math.atan2(this.y - playerY, this.x - playerX) - 2.35;

    // Move towards the player
    this.x += Math.sin(this.rotation) * this.speed;
    this.y -= Math.cos(this.rotation) * this.speed;
}

```

How can I get the sprite to just move towards the player in a straight line rather than a circle? I found a good example but it uses XNA `Vector2`'s so it's not working with x and y positions directly.

# Answer
> 6 votes
I'm not particularly sure where that 2.35 value is coming from, which could be adding artifacts to your code, so I've removed it from my answers.

That being said, your basic intuition seems to be correct, however you have your `sin` and `cos` switched. Also, I'd wager that since you're already taking the difference between two (X,Y) coordinates, that you do not need to subtract the Y value since you're in the reference frame of the sprite itself. Finally, if you're trying to move towards the player, then your vector math is wrong. Given two vectors **a** and **b**, (**a** \- **b**) is the vector in the direction from **b** to **a** and (**b** \- **a**) is the vector in the direction from **a** to **b**.

Perhaps what you wanted was:

```
Enemy.prototype.update = function(playerX, playerY) {
    // Rotate us to face the player
    this.rotation = Math.atan2(playerY - this.y, playerX - this.x);

    // Move towards the player
    this.x += Math.cos(this.rotation) * this.speed;
    this.y += Math.sin(this.rotation) * this.speed;
}

```

A better way to encode this is to separate the rotation from the movement. If all you're doing is moving towards the player, then you shouldn't be worried about what way you're facing:

```
Enemy.prototype.update = function(playerX, playerY) {

    // Calculate direction towards player
    toPlayerX = playerX - this.x;
    toPlayerY = playerY - this.y;

    // Normalize
    toPlayerLength = Math.sqrt(toPlayerX * toPlayerX + toPlayerY * toPlayerY);
    toPlayerX = toPlayerX / toPlayerLength;
    toPlayerY = toPlayerY / toPlayerLength;

    // Move towards the player
    this.x += toPlayerX * this.speed;
    this.y += toPlayerY * this.speed;

    // Rotate us to face the player
    this.rotation = Math.atan2(toPlayerY, toPlayerX);
}

```

# Answer
> 3 votes
I would solve this using simple algebra.

Given your sprite's position and the target location you should be able to find the slope of the line that would connect the two coordinates. This can be done using the following equation:

Essentially, the numerator (top number) is going to be velocity you apply on the Y axis and the denominator (bottom number) is going to be the velocity you apply to the X axis. These numbers already have a bit of a bias on speed though and could improperly influence how fast you end up moving. As a result, we want to normalize this into a single unit.

To normalize this into a unit vector you first must find the length (aka magnitude) of the vector using the equation `sqrt((x * x) + (y * y))`

Once you've found the length you can convert it to a unit vector by dividing the x and y values by the length.

Multiply this unit vector by your speed and you should be properly moving towards your target.

In code this would look something like:

```
var run = playerX - this.x;
var rise = playerY - this.y;
var length = sqrt((rise*rise) + (run*run)); //pseudocode
var unitX = run / length;
var unitY = rise / length;

this.x += unitX * this.speed;
this.y += unitY * this.speed;

```

You might need to do some fiddling with the sign or the order of the numbers depending on what direction is up, etc. but the concept should apply.

---
Tags: javascript, sprites, movement, html-canvas
---


title: Moving Sprite With Physics Frame

text:
# Question
Title: Moving Sprite With Physics Frame
Normally, a physics frame in pink (see image below) gives the body for detecting hit signal. It usually either falls down or lifts up depending on the gravity orientation. The question is: *Is it possible to move or manipulate sprite through X and Y coordinate without needing to use the gravity code from a physics engine like **bodyeditor-loader-sources.jar** (e.g. `ballBody.setGravityScale(100.1f);`) so that I can move simply either by dragging, change the value initially, or moving it by D-pad?*

# Answer
I used DynamicBody for my missiles, set their gravity scale to 0f, and I could move them freely the way I wanted to.

You might want to refer to Box2d documentation, chapter 7.1. You can set their flag isSensor to true, if you want them to report collisions instead of respond to them according to physics laws.

But from now on, you should use your physical body location as sprite location (remember, that Box2d uses meters as dimension unit, so you need to convert it to units your using internally for your objects; otherwise you will get different result for physics-representation and graphical-representation).
> 2 votes

# Answer
A simple way to move the body on the X, Y axises is using impulses or forces.

You could manipulate the impulses with the gdx input processor.

Example :

```
  If (Gdx.input.isKeyPressed(Keys.LEFT)) {
            //move the body to the left
             Body.applyLinearImpulse(new Vector2(-1 , 0), body.getPositon());
}

```

Note that in the vector I put -1 so the ball will recieve multiple impulses and it's width wil decrease by 1. P.S: If you insert a positive value, the body will move right
> 1 votes

---
Tags: java, physics, libgdx, physics-engine
---


title: QuadTree Subdivision Issue

text:
# Question
Title: QuadTree Subdivision Issue
I have been working on a level-of-detail program. Right now I have the rough structure down (splitting of quads without condensing of quads). But the problem is that when you try to split certain quads after they are 1/8 the size of the original they sometimes do not split and the quads that should have been placed in that spot are in another place. I think I just need someone else to look at this code, I believe the problem rests in the index of the quads... Here is the main code:

```
public Quad(Vector3f v1, Vector3f v2, Vector3f v3, Vector3f v4,float size,int x, int y,boolean has,float pI, float pI2){
    first = v1;
    second = v2;
    third = v3;
    fourth = v4;
    width = size;
    index1 = x;
    index2 = y;
    children = has;
    parentIn1 = pI;
    parentIn2 = pI2;

}
public static ArrayList<Vector3f> makeVerts(Vector3f p, int x, int y, float increment){
    ArrayList<Vector3f> list = new ArrayList<Vector3f>();
    Vector3f back_left = new Vector3f ((float)x*increment, 0 , (float)y*increment).add(p);
    Vector3f front_right = new Vector3f ((float)(x*increment) + increment, 0, (float)(y*increment)+increment).add(p);
    Vector3f front_left = new Vector3f ((float)x*increment, 0 , (float)(y*increment)+increment).add(p);
    Vector3f back_right = new Vector3f((float)(x*increment) + increment, 0, (float)y*increment).add(p);

    list.add(back_left);
    list.add(front_left);
    list.add(front_right);
    list.add(back_right);
    return list;
}

public static void create(Quad quad, int i, int ii){
    quad.children = true;
    i+=quad.parentIn1;
    ii+=quad.parentIn2;
    System.out.println(i+ " "+ii);
    Vector3f parent = new Vector3f(i*quad.width, 0, ii*quad.width);
    //System.out.println(parent + " "+ toString(quad));
    if(quads == null){
        quads = new Quad[2][2];
        for(int x = 0; x<2; x++){
            for(int y = 0; y<2; y++){
                float growth = quad.width/2;
                ArrayList<Vector3f> points = makeVerts(parent,x,y,growth);
                Vector3f p1 = points.get(0);
                Vector3f p2 = points.get(1);
                Vector3f p3 = points.get(2);
                Vector3f p4 = points.get(3);
                quads[x][y] = new Quad(p1,p2,p3,p4,growth, (int) (x+quad.index1),(int)(y+quad.index2),false,quad.index1,quad.index2);
                list.add(quads[x][y]);
        }

    }
}

    }

```

In addition here is the code that creates the first quad and divides it into four:

```
Vector3f v1 = new Vector3f(0,0,0);
Vector3f v2 = new Vector3f(0,0,32);
Vector3f v3 = new Vector3f(32,0,32);
Vector3f v4 = new Vector3f(32,0,0);
Quad q = new Quad(v1,v2,v3,v4,32,0,0,false,0,0);
Quad.create(q,0,0);
v.addAll(Quad.getPoints());
Quad.reset();

```

And the code that divides quads depending on one's distance:

```
   for(int i = 0; i<Quad.list.size(); i++){
        Quad q = Quad.list.get(i);
        Vector3f center = Quad.getCenter(q);
        float width = q.width;
        float distance = center.distance(cam.getLocation());
    if(width/distance >= .85 && !q.children){
        Quad.reset();
        Quad.create(q,q.index1,q.index2);
        VertexBuffer vb = mesh.getBuffer(Type.Position);
        v.clear();
        v.addAll(Quad.getPoints());
        verts = new Vector3f[v.size()];
        v.toArray(verts);
        vb.updateData(BufferUtils.createFloatBuffer(verts));

```

parentIn1&2 are the indices of the parent quad. Index1&2 are the indices of the quad. Each time a quad needs to divided the "create" method is run... Just for an idea of what is happening here is a shot of the actual scene. On this run I zoomed in exactly on the center of the quad and this was the result.. Thanks for any and all help, it is much appreciated.

# Answer
> 2 votes
I fixed the problem... Here is the revised code for the method "create()" if anyone is interested, Thanks for the time:

```
public static void create(Quad quad, int i, int ii){
    quad.children = true;
    i*=2;
    ii*=2;
    Vector3f parent = new Vector3f(i*quad.width/2, 0, ii*quad.width/2);
    System.out.println(parent + " "+ toString(quad));
    if(quads == null){
        quads = new Quad[2][2];
        for(int x = 0; x<2; x++){
            for(int y = 0; y<2; y++){
                float growth = quad.width/2;
                ArrayList<Vector3f> points = makeVerts(parent,x,y,growth);
                Vector3f p1 = points.get(0);
                Vector3f p2 = points.get(1);
                Vector3f p3 = points.get(2);
                Vector3f p4 = points.get(3);
                quads[x][y] = new Quad(p1,p2,p3,p4,growth,(x+i),(y+ii),false,quad.index1,quad.index2);
                list.add(quads[x][y]);
        }

    }
}

    }

```

---
Tags: level-of-detail, quadtree
---


title: Implementing a basic jump in libgdx

text:
# Question
Title: Implementing a basic jump in libgdx
I have seen the document for libgdx and managed to move the character and also to implement bounds but the document does not show how to implement jumping.

I have downloaded the superjumper demo code but it is too confusing for me. Is there anyone here who can guide me?

Say for example we have a spritebatch:

```
Spritebatch batch;

```

How can I implement a jump for this spritebatch when the screen is touched?

# Answer
> 6 votes
> **NOTE:** Apparently, in libgdx, the origin is at the lower left corner of the screen. You should switch "IncreaseYCoordinate" with "DecreaseYCoordinate" in your actual code.

Jumping, at the base, is language and framework agnostic. You should look at it that way if you wish to learn anything. "Jumping", especially in 2D games, is the process of modifying a character's (sprite's) position on the screen so that he or she **appears** to be jumping. That's all. You just draw your character at a different height on each Draw call, so it appears to be moving vertically (jumping).

I'm not exactly familiar with libgdx, but I presume you're doing something like:

```
batch.draw(someTexture, 100, 350);

```

Where 100 is the X coordinate and 350 the Y coordinate of the drawn texture. This obviously makes your texture show up at the position described by the vector (100, 350). I am currently supposing that the origin (0,0) is the upper left corner of the screen (increasing the Y coordinate makes your sprite show up lower on the screen).

Now, if you were to decrease the Y coordinate, like:

```
batch.draw(someTexture, 100, 349);

```

Your texture would get drawn at a higher position on the screen.

```
batch.draw(someTexture, 100, 348);

```

And even higher, now.

Simple, is it not? The first thing you need to do is to get your sprite to continuously ascend until he should stop doing so. Then, the sprite should go back to its original position by descending. Since you have not posted any actual code, and the question is a bit broad, I can only give some rough guidelines.

* Store your sprite's position in a Vector-like structure. Or two variables, one for the X coordinate, and one for the Y coordinate.
* The jump should go smoothly. Keep two variables: "speed" and "originalSpeed". These should be integers;
* Keep a state flag, that tells the Update() function when to increase or decrease the sprite's Y coordinate. This can be an **enum** with the values **{ Ascending, Descending, Standing }**
* Intercept the touch event, and when it happens, set the state flag to **Ascending** (if it's not already set to Ascending);
* In the Update method, you should change the Y coordinate of the sprite considering its current state. Thus:

```
if (State == Ascending)
{
  //We're ascending. Decrease the Y coordinate of the sprite by the speed.
  DecreaseYCoordinateBy(Speed);
  DecreaseByValue(Speed, Value); //The character needs to jump smoothly, so the speed should decrease as he ascends.
  if (Speed <= 0)
  {
       ChangeState(Descending); //If speed is <= 0, then the character should fall down.
       Speed = 0;
  }
}
else if (State == Descending)
{
  //We're descending. Increase the Y coordinate by the speed (at first, it's 0).
  IncreaseYCoordinateBy(Speed);
  IncreaseByValue(Speed, Value); //Increase the speed, so the character falls gradually faster.
  if (CurrentYCoordinate >= OriginalYCoordinate)
  {
       //If we reached the original Y coordinate, we hit the ground. Mark the character as standing.
       ChangeState(Standing);
       CurrentYCoordinate = OriginalYCoordinate;
       Speed = OriginalSpeed;
  }
}

```
* Drawing is done like:

```
batch.draw(yourSprite, CurrentXCoordinate, CurrentYCoordinate);

```

Obviously, you need to enter your own values for the original coordinates and speeds. Tweak them to find the values that best suit your needs. This is not exactly the "best" way to do it, but should give you a starting point. You may want to impose some limitations on the falling speed, so that it increases only up to a certain amount. You could (and should) use different speeds for jumping and falling too.

Also, this is not libgdx related, but might give you a few hints:

http://www.xnadevelopment.com/tutorials/thewizardjumping/thewizardjumping.shtml

I definitely recommend that you search for as many such tutorials as possible, even if they're not libgdx related. Jumping is a concept that can be learned from just about any source.

# Answer
> 1 votes
For making a sprite "jump", it needs to be assigned to a box2d body. Then you can apply an linear impulse to the physic body when screen is touched.

Example : For making the code more simplier, you can begin with inserting something like this in your render() method :

```
If (Gdx.input.isTouched()) {
          Body.applyLinearImpulse(new Vector2(0, 20), body.getPosition());

```

}

Doing so, every time you touche the screen, your ball will jump. You can change the value of the vector if you want to change direction, force of the impulse.

P.S: I strongly recommend you to read the box2d manual or see examples on internet regarding the creating and manipulating bodies in this engine.

# Answer
> 1 votes
My advice would be to have another look at the superjumper code. The jumping code in the superjumper demo is here.

Lines 69-79 set up jumping in response to hitting a platform or hitting a spring. In both cases this is done by setting the vertical velocity and setting Bob's state to jumping.

```
public void hitPlatform () {
    velocity.y = BOB_JUMP_VELOCITY;
    state = BOB_STATE_JUMP;
    stateTime = 0;
}

public void hitSpring () {
    velocity.y = BOB_JUMP_VELOCITY * 1.5f;
    state = BOB_STATE_JUMP;
    stateTime = 0;
}

```

The actual movement takes place in the *update()* method (lines 37-61). Here the acceleration due to gravity is applied to the velocity, then the position is updated by adding the velocity itself. Note that all updates are multiplied by deltaTime to take into account that the rate at which *update()* is called may not be constant.

Here's the snippet that does that.

```
public void update (float deltaTime) {
    velocity.add(World.gravity.x * deltaTime, World.gravity.y * deltaTime);
    position.add(velocity.x * deltaTime, velocity.y * deltaTime);

```

As for detecting whether the screen has just been touched, use *Gdx.input.justTouched()*. For example (this is illustrative more than accurate):

```
if (Gdx.input.justTouched() && state != JUMPING) {
    jump();
}

```

---
Tags: android, libgdx, jumping
---