text:
Practical balance of "chance" video game mechanics
I've been a small games developer and designer for years, and I've recently begun working on more serious design documents for bigger projects.
A common theme I'm running in to is imbalance when it comes to "chance" RPG mechanics.
Critical Strike Chance. Chance to Hit/Dodge/Miss/Parry/Block so on.
The biggest problem in modern RPG games is factoring in Haste (Attack Speed), since it compounds so aggresivly with the other base mechanics.
Obviously, the more times a player attacks, indirectly increases their "rate" of critical strikes, or hits. This creates an immense imbalance, and most of the solutions come in the form of capping haste or utilizing diminishing returns or to killing the big stat increases.
As a designer and player, I don't feel this is a healthy way to deal with the issue. It's not a "fun" solution. Recently, gamers seen Blizzard's answer to this Haste issue in Diablo3, by halfing the stat increases on most all items.
Here is a practical example:

50% chance to critically strike, with 1 attack per second = on average 0.5 critical strike per second.
50% chance to critically strike, with 2 attacks per second = on average 1 critical strike per second.

The second situation is by far favorable, rather than increasing your Critical Strike Chance alone, since not only will you see more larger numbers (or hits in terms of a miss chance mechanic) per unit of DPS, you'll also be hitting more and games with Proc Chance mechanics also benefits.
More Complex games balance such things with Internal Cooldowns and Weighing the stats against each other, but often times Haste still comes out on top as being the supremely powerful stat.
Is it practical to instead use a Rate to decide weather or not something happens vs stat weights, capping and cooldowns?
My simplified example is:
Critical Strike RATE = Crit Chance / Attacks Per Second
The result is basically a simple stat weight system. Mechanics such a proc chances still benefit from Haste, however it may be easier to change the damage output of attacks and abilities to reflect the balance.
This keeps enjoyable haste mechanics in the game, which are fun to play. It also creates more depth for slower attack builds, rather than just an ability or proc benefiting from slow weapons.
Is this a near-sighted solution? Are there working examples of games currently on the market that don't cap or punish "haste" character builds?

Multiplying chances doesn't work like that. 50% chance is half as likely as a 75% chance.

This isn't a measure of chance as per hit. It's a measure of the rate of critical strikes per unit of damage per second. In the second example you're nearly guaranteeing yourself 1 critical per second of damage.

@Mr.Beast: They don't work like that either. ;-)

@robphill It's 75%. Think of it this way: You flip two coins. What are the odds that one of them is heads (critical)? You have 4 possible outcomes HH - HT - TH -TT     i.e. in 3/4 cases, you have heads (you crit) and only 1/4 cases you have two heads (two crits)

The problem you are describing is not necessarily about haste. It is about the multiplicative effects of increasing different stats. Haste increases hits per second, which increases damage and anything with a chance to happen per hit. Another example would be increasing +crit dmg which then increases the value of any +crit % chance.
You could benefit from extracting bonus hit procs from the critical hit event.
Instead of a talent that inflicts poison on the target when a critical hit occurs, give the proc its own independent chance of occurring. This will still scale with haste, but increasing critical strike chance will not increase the value of the poison talent.
Any on-hit chance is going to be affected this way by haste. World of Warcraft uses a proc-per-minute (ppm) implementation for things like trinkets that activate on hit or spellcast. This is primarily intended to reduce the randomness and clustering of procs.
If that is still distasteful to you, perhaps what you are looking for is not a haste mechanic, but something more akin to windfury in WoW. Pure haste percentage is always going to need high numbers before it becomes noticeable and those high numbers are what cause problems with other systems.
If you are just looking to see extra normal attacks, add a stat that gives a chance on hit to give a free extra normal swing that cannot proc a crit or any other special attack. In WoW this ability is called windfury and it is always more exciting to see than a flat haste percentage. Numerically is not that different from a critical hit, but it can still be dodged, trigger thorns, etc. like a hasted attack. If you want these extra hits at a regular interval, implement a ppm system.

The multiplicative nature of these stats are not the cause the imbalance you refer to. In fact, they tend to prevent one single stat from being dominant. For example, higher attack speeds increase the usefulness of boosting attack damage. Doubling either value will have the same effect on the DPS, but most systems automatically enforce doubling numbers that are already high is quite difficult.
As the player progresses, their increase in attack damage is often opposed by an increase in the enemy's defensive capabilities, which can scale almost indefinitely, unlike attack speed, which has a narrow 'logical' range. I suspect this is the main reason developers turn to caps or diminishing returns.
There are other options, however. By defining the on-hit critical strike chance as the ratio of crit statistic and attack speed, you effectively end up with a fixed estimate for the number of critical hits per unit time, removing a multiplicative relation from attack speed. A very common alternative is to use a stamina pool that haste quickly depletes. In other games, attack speed may have limited merit due to it being uncommon for an enemy to stay in attack range long enough for you to land more than one hit anyway. As for critical strikes, a lot of games don't bother with probabilities, but use different criteria, such as attacking from behind.
Most importantly, if you can't find a way to make it fun, eliminate the system altogether. Numerous RPGs don't even have variable attack speeds or critical strikes. Arbitrarily making equations more complicated doesn't add any interesting depth.

There's no intrinsic problem regarding critical hits etc. The small chance of doing critical damage can be disregarded and considered a small boost to the average damage if you prefer.
Obviously with any random event that occurs periodically, as you shrink the period the frequency of the event increases exponentially (because if the period is infinitely small, the frequency is infinitely high). The answer is to ensure that the period cannot approach zero, which means a lower bound on the period.
If you don't want to put a lower bound on it, you would have to decrease other capabilities at at least the same rate or higher. If you decreased them at a slower rate, then it would still end up tending towards infinity as the period shortens. But if you decrease at a higher rate, there's no point shortening the period as the player gets no benefit. So a clamp seems the most reasonable solution.

Here is a practical example. Think of damage in terms of units of DPS, or active combat time.
  50% Chance to Crit, with 1 attack per second = (roughly)50% Critical Strike RATE per DPS unit.
  50% Chance to Crit, with 2 attacks per second = (roughly)100% Critical Strike RATE per DPS unit.

No, the second example gives you 75% chance of at least 1 critical strike per second. However it gives you an average of 1 critical strike per second. These are different things!

Correct. I'm aware of the average chance in the second example, my implication is the rate, as you understand it being 1 crit per second. They are different things, and that's the point of an analysis between chance and rate. When you're looking at units of damage on a per second basis, the 100% rate is an accurate assumption, it's basically the exact same as you said: an average of 1 critical strike per second.

And that is entirely what is intended. So... did the first part of my answer address your question or not? It's not entirely clear what you're after since you're using some fairly specific terminology.

Partially. I was wandering if there were any examples of decreasing a random chance at the exact same rate of frequency. My specifically, I havn't ever seen this in practice and am unsure if it's a more "fun" system for the player, opposed to a capping system.
However, I think breaking up crit specific mechanics in a category of play all their own is interesting gameplay-wise.
As in, a "assassin" archetype has the ability is crit, whereas a mage or warrior archetype doesn't.
I'm looking for something a live talk, rather than specific to a prototype/proof of concept or design documentation.

I don't understand what you mean by "decreasing a random chance at the exact same rate of frequency". If you're suggesting that the chance of a 'critical' event could be done per second rather than per hit, so speeding up hits didn't affect criticals as well, then sure, it could, easily. As for whether it would be more fun, nobody's invented a "Funometer" yet.

You're right, there is no metric for fun. I also know it's very possible. I was searching for designed alternatives, opposed to the status-quo approach.
From a purely design perspective, a notion of "fun" comes with fluid design that isn't counter-intuitive to how it's used in play. I've rarely seen solutions to simple design mechanics, that fit the mechanic attempting to be addressed.

I'm still not entirely sure what exactly you're hoping to read or learn here, so let's hope someone else has an answer for you.

Instead of giving just flat +crit chance bonus, you could adopt a stat which determines your crit chance. This is usually included in precision/dexterity/agility, depending on the game. Precision requires more  and more stat points in order to get an increase in crit chance as you go higher, so at a certain point, the return on invest is so low, it would be better to invest in another stat (usually strength) to increase your damage.
This would still allow a player to create a character that crits (nearly) 100% of the time, but it's other stats (including strength) would be very low and it would have to rely on special effects caused by crit damage (like bleeding, life steal,...)
IAS can be countered with enemy curses that cause you damage every time you attack, or by simple making it a temporary activated ability with a downside: take 50% more damage while active, or cause less damage.
try to keep the damage boosting abilities in different attribute lines: crit chance, attack damage, crit damage and IAS should never be in the same line. (IMHO, I wouldn't put IAS in a stat line, since it has the potential to make other things overpowered, as you pointed out).

A higher haste value doesn't necessarily have to reflect a higher amount of critical hits. Many games use two different stats for calculations - base stats, and modifiers. (D&D is a great example). Why not calculate critical hits based on the base of the haste stat, but still reflect the critical chance? For example, a level 1 character has an unmodified base haste of 1. He hits one time per second. Once per second he has a calculation that gives him a chance to critically hit. The character then levels up to 2. He now has a haste level of 2 that allows him to attack twice per second. Critical chance is still calculated on base haste which is 1 allowing him to still only get a maximum of 1 critical hit per second. This is the route that some games go down, and often it's not quite as simple as I've described, but it's something to think about. It depends on the game, the situations and the core mechanics.

authors: Ирина Димитрова


text:
apply non-hierarchial transforms to hierarchial skeleton?
I use Blender3D, but the answer might not API-exclusive.
I have some matrices I need to assign to PoseBones. The resulting pose looks fine when there is no bone hierarchy (parenting) and messed up when there is.

I've uploaded an archive with sample blend of the rigged models, text animation importer and a test animation file here:
http://www.2shared.com/file/5qUjmnIs/sample_files.html
Import the animation by selecting an Armature and running the importer on "sba" file.
Do this for both Armatures.
This is how I assign the poses in the real (complex) importer:
matrix_bases = ... # matrix from file
animation_matrix = matrix_basis * pose.bones['mybone'].matrix.copy()
pose.bones[bonename].matrix = animation_matrix

If I go to edit mode, select all bones and press Alt+P to undo parenting, the Pose looks fine again.
The API documentation says the PoseBone.matrix is in "object space", but it seems clear to me from these tests that they are relative to parent bones.

Final 4x4 matrix after constraints and drivers are applied (object
  space)

I tried doing something like this:
matrix_basis = ... # matrix from file
animation_matrix = matrix_basis * (pose.bones['mybone'].matrix.copy()  * pose.bones[bonename].bone.parent.matrix_local.copy().inverted())
pose.bones[bonename].matrix = animation_matrix

But it looks worse. Experimented with order of operations, no luck with all.
For the record, in the old 2.4 API this worked like a charm:
matrix_basis = ... # matrix from file
animation_matrix = armature.bones['mybone'].matrix['ARMATURESPACE'].copy() * matrix_basis
pose.bones[bonename].poseMatrix = animation_matrix

pose.update()

Link to Blender API ref:
http://www.blender.org/documentation/blender_python_api_2_63_17/bpy.types.BlendData.html#bpy.types.BlendData
http://www.blender.org/documentation/blender_python_api_2_63_17/bpy.types.PoseBone.html#bpy.types.PoseBone

You could add intermediate bones, e.g. make a spine/snake of bones, forming a rigid hierarchy and using the intermediate bones to position the real bones.

I don't know if this is the correct answer (as I know relatively little about blender's behavior), but are the bones long enough? It kind of seems like the deformation is not being applied properly because of the way the bones are weighted.  I am used to seeing other skeleton systems where the end of one bone touches the beginning of the next - here they appear to not connect.

In Blender connected bones also means parented bones. Connection signifies a hierarchy, so no...

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Can someone explain this occurrence with a fbx model in xna?
Because this is kind of weird to explain, let's show you what I mean.  This is in my game.  When I import this base ship model, it should be at (1000,1000,1000), but the model acts like it's at (1000,1000, 0).  Note it is positioned correctly when I use a .x model.  So it has to be the model.  I need to know what's wrong with it.
Here is the model file, tell me if anything is wrong with it: https://dl.dropbox.com/u/92848165/station2.FBX
https://i.stack.imgur.com/CVUed.jpg
EDIT: The model works if you import it into Google Sketchup...but you lose the textures, not very nice.

Is the model centered to the origin inside your modelling program? Are you applying the correct transforms to all of its bones before drawing it? (And did you post this to /r/gamedev? I think I saw a simillar screen before).

I have no idea, it looks so in the fbx file.  Take a look yourself.  I never posted anything related on r/gamedev, do you think they know?

If Google draws it properly, then there's something wrong in your source code. Are you using the default Content Pipeline to load the model?

@Marton Yes, obviously.  I figured out that it was the transformations that effected the models.  If you move them to the center, it actually doesn't matter, cause even if it looks at 0,0,0 it will be drawn at how much you moved it.  You need to Freeze Transformations and Delete Object History.
So it obviously wasn't my source  code like you said :P

Well, then whose source code was it?

I realize that this is really really late....
The only solution to this that crosses the mind is that the model isn't centered in the origin....
Try making the model in a different software (importing / exporting again).... Use blender as it is free and is pretty easy to use:
http://www.blender.org/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Should the frame rate be consistent or is it normal for it to jump around?
As I commented on a post, I started wondering if it was correct or not (the comment, not the answer). And I'd like to straighten that out.
Although not needed as info, here's the link to the question: Scene management for 3D editor
My comment: "Wouldn't mind that much about the framerate, as long as it stays above 60. you can get away with 30 even."
Still I think if the frame rate is over 30, the real time rendering stays as a good animation. But sometimes I read that people restrict the render() to 60fps or 30fps for performance. This could/would remove all unneccecary calculation wich we can't see anyway. Although true, they (sometimes) claim it is an optimization.
When a scene will render more objects, the fps will drop. Think that is normal.
So what's the deal with fps, should it stay more or less the same even when you turn the camera 90 or 180 degrees, or only when keeping (almost) the same view?

Hey, update() has nothing to do with rendering. Did you mean render() or draw()?

The render(), you're right although the context would be the same. Will update() it so the question renders() correct.

Cool. (Also, what do you mean "the context would be the same"?)

The update is the part wich does the culling and affects the fps, the update just merely draws the scene. However, those cliams I mentioned are about the restricting the update. But the two functions comes in - imho - a pair where you first collect information (update) and then send (render) the data.

The comment is both right and wrong at the same time. Framerate is very important to a well polished product. You don't want the player to suddenly pop into a view where their framerate tanks.
Having said that, when a game is being developed, there normally is a specific hardware level that is being designed to - ie, the minimum spec that is expected for the game be run on - and you should be looking for a minimum framerate on that environment. If it is higher on bigger machines, great - but never drop below your expected framerate on that built. That minimum framerate is normally 24 (which is what the human eye can pick up) - but that is also not quite true. While the human eye does work on around 24 "frames" per second, switching from a white to black screen is noticed, so the smoother you can make the transition, the better it will look to the viewer.
When it comes down to framerate and you are seeing a drop in a particular scene, the real question to ask is "Is the drop in framerate here worth what the player is seeing?". So, if you are playing a 1st person shooter and the center of a level drops in framerate by 20 fps, but the center of the level is a gorgeous view to an amazing model that will no doubt make the player oogle over, it might be worth it. If you can limit what they see by occluding certain parts of it, then it might be better. If you can reduce the poly size of the model so that it is still as visually appealing as before, but it doesn't tank fps, then even better.
tl;dr fps is always a tradeoff between how good something looks and how quickly you can render the environment.


text:
Should I amortize scripting cost via bytecode analysis or multithreading?
I'm working on a game sort of thing where users can write arbitrary code for individual agents, and I'm trying to decide the best way to divide up computation time.
The simplest option would be to give each agent a set amount of time and skip their turn if it elapses without an action being decided upon, but I would like people to be able to write their agents decision functions without having to think too much about how long its taking unless they really want to.
The two approaches I'm considering are giving each agent a set number of bytecode instructions (taking cost into account) each timestep, and making players deal with the consequences of the game state changing between blocks of computation (as with Battlecode) or giving each agent it's own thread and giving each thread equal time on the processor.
I'm about equally knowledgeable on both concurrency and bytecode stuff, which is to say not very, so I'm wondering which approach would be best. I have a clearer idea of how I'd structure things if I used bytecode, but less certainty about how to actually implement the analysis. I'm pretty sure I can work up a concurrency based system without much trouble, but I worry it will be messier with more overhead and will add unnecessary complexity to the project.

probably you are losing the main focus, in java you have the JVM that slow down every operation, look at minecraft and how inefficient it is, how you are supposed to optimize something in java? the best JVM for performance is probably the Dalvik that is a really small JVM with a fast GC, but optimizing this kind of things in java just doesn't make sense to me, if you want performance use C++

It sounds like your agents are only reading world state and making decisions based upon it -- is that true? Do they ever write to or otherwise modify state?

I think you should force your users to be concerned about how long it takes to compute an action.  If they are taking 100 seconds or more to "decide" on something, I would be concerned that maybe your players are not trying hard enough to come up with "fun" and quick solutions. I don't quite understand your use case, but I don't think you want to give each player all the time in the world to make a single decision.

A casual analysis:
Why threads?
Simply running each user's code in a separate thread is easy. But two threads don't always get equal processor time.
The classic example is to start two threads, one of which prints A and the other B. You'll see ABABAB a lot, but eventually ABABBA happens, sometimes even ABBBA, sometimes even ABBBBA. Most operating systems provide no guarantee that threads get equal time in the short term.
Depending on the game though, a small short-term advantage may be negligible.
Why bytecode?
Bytecode restrictions get you closer to absolute fairness, as they are "closer to hardware", or as close as you'll likely want to get. Allowing only a certain number of bytecode instructions per tick from each entity is equivalent to implementing fair multithreading (except, of course, the loss of multi-core optimisations that the OS cannot do on custom "threads"). Battlecode allows 6000 bytecode instructions (of Java?) per tick.
Mojang's 0x10c (multiplayer, in development) emulates DCPU-16 architecture, which admittedly is a pretty ridiculous length to take this to. However, it is an example of going all the way to (at least virtual) hardware.
tl;dr
If short-term differences are important, study the possibility of bytecode. Else threads.

+1. I would even go so far as to say, "80% of the time, optimise your single threaded code". In other words -- focus on the bytecode unless you have every reason to believe that even with nigh-faultless efficiency, you still won't have sufficient CPU time.

I would go even further than @NickWiggill, and say "if you have to ask, then don't use threads."


text:
global transform to local transform?
If an object is attached to another one and you need to set its position, rotation and scale in global space, what do you do to get the local versions of these values, knowing the same values for the "parent" object?

Position, rotation and scale in relation to what?

You will want to store translation, rotation, and scale independently to make this easier (and in various cases, faster), but matrix decomposition will work.
The method for each of the three parameters is different but extremely easy.
First, let's look at what you already know: how to get the world position from the child's local position and its parent's world position.
For translation, simply add the parent's translation from the child's.  If the parent is at (10,2,7) and the child's local translation is (1,-3,4), then the child's world position is (10+1,2-3,7+4) = (11,-1,11).
For rotation, apply the parent's rotation to the child's.  If you're using a simplified quaternion class, this would mean simply multiplying the parent's rotation against the child, probably using an overloaded operator, e.g. world = parent.otation * child.rotation.  Note that that is not the "proper" notation for quaternions, but it's how they're generally implemented in C++/C#/Java math libraries.
For scale, multiply the components of the parent against the child's.  If the parent is (2,2,2) and the child is (0.5,1,2), then the world scale is (2*0.5,2*1,2*2) = (1,2,4).
To go the other way, simply do the complementary operations.
To get the local translation, subtract the parent's world translation from the child's world translation.  Using the same sample numbers from before: (11-10,-1-2,11-4) = (1,-3,7).
To get the local rotation, you'll want to multiply the child's world rotation by the parent's conjugate.  The conjugate is simply the original quaternion with the vector parts negated, e.g. (-x,-y,-z,w).
To get the local scale, multiply the child's world scale with the reciprocal of the parent's world scale.  With the previous example numbers, the parent had a uniform scale of 2, so its reciprocal would be a uniform 0.5:  (1*0.5, 2*0.5, 4*0.5) = (0.5,1,2).

Maybe it would be helpful for others to also mention what needs to be done when rotation is in euler or a rotation matrix.


text:
Making online battles take time
Let's say I have an account on an MMORTS and I send my 10,000 strong army to a location on the map. I then shut off my computer.
Another player gives orders to his 10,000 strong army to walk to the same location and attack anyone located there. He then turn off his computer.
After 30 minutes when his 10,000 guys arrive at the scene the battle begins. Now killing 10,000 guys where both armies are using the same skill and weapon might take several hours.
Let's say I turn my computer on again and find the raging battle and that I only have 4500 soldiers left, so I decide to pull my army back.
This type of ongoing battle happens on the server. How could this be accomplished? I'm thinking JavaScript / PHP technologies. I'm thinking that there should be some sort of dice system to each attack so it could end with one side winning with 1500 men left even if they started with equal amount. Is there some sort of clever logic that would not require 20,000 calculations per frame to calculate each hit and and parry for every unit?

It looks like you might be asking two different questions, so I'll answer them each separately (though one may influence the other).
Taking Time: What you want is that the battle actually executes over a longer period of time, rather than just as quickly as can be calculated. This gives the user the impression that something is actually hapenning and allows them to change their orders during the battle. Here a timeslicing approach makes sense. Presumable you will be hosting several battles on the same server, so you'd probably need to do this anyway.
In this approach each of your active games represents an object on the server. Now your server will poll each active game at a fixed interval. Say every 30s: you can adjust upward to lower total load and downward to improve user real-time feedback. Each interval you will simply step each active game by 30s (scaled to the world time).
Calculations: Trying to represent 10000 units as 10000 objects is simply not going to be possible. Perhaps if you write in C++ and have a very optmized algorithm you could do it, but you still wouldn't be able to support many active games on one server. Instead what strategy games tend to do is lump together units into groups. So you have 500 rifleman, 2500 infinitry, 20 artillery, etc. That is, reduce your battle to a small number of actual objectds.  These cumulative objects can then fight each other in turn.
In the simplest model, say for infinitry, you could simply multiple per unit HP times the number of units to get one virtual infinity unit with a really high HP, and also a really high firing power.  This is perhaps not ideal, but it is a decent logical starting point. Here you don't really do pure die roling anymore, you'll be using statistical projections (easier than it sounds). So if each unit has only a 10% chance to hit, the logical group will simply do 10% of its total damage each round. Again, simplified, but gives you the basic idea.

I see two problems here - optimizing the battle on the server and allowing the player to view and change the battle before it is finished.
First things first - optimizing the battles. You need to design combat in rounds, and roll dices for each unit separately within each round, giving you 20000 computations per round - each unit attacks one other unit and defends from one attack. You can design the combat system so that it will last a small amount of rounds, for instance a 100 for 10000-unit armies. If you find your battles take longer, you could make them more 'bloody' using various techniques - make combat between opponents more random (higher standard deviation), penalize fighting between the same 2 units for more than 2 rounds etc. This should give you a required total number of 'computations' in the millions per one battle of 10000 units, which seems sensible. Moreover, it is easily breakable down into smaller chunks or parallelizable from the other server work.
A different approach you could try is using Lancherster's laws for mathematically modelling battles.
Once you have that, you can look at your second problem differently. You can precompute battles and store them as a series of states, each state corresponding to a combat round. Displaying battles is, like many things in games, interpolation - you know in what timeframe each round should occur, so when displaying the battle at any given time you can choose the two nearest precalculated rounds and show to the player a dynamically-changing state that is somewhere in-between. You don't have to be precise; nobody is interested in exact numbers. If the player decides to retreat, you can confirm the action instantly and send it to the server, which will recalculate part of the battle - from the current (or next) frame onwards. If you give the player instant feedback, he will accept that the action is non-instantious and that there might be more casualties that the last displayed number (it's believable that receiving an order and retreating take time). Other events - reinforcements, change of tactics, spells/abilities etc - can all be handled in the same way, by recalculating the battle from the given moment onwards.
In essence, what I'm saying is discretize the battle, store it, interpolate for the purposes of showing it to the player and recalculate when a player decision is made.


text:
How to render metaballs?
How  to render metaballs?
I am a Python programmer familiar with the Panda3d and Blender3d APIs. My math kinda sucks, but I know enough to write game logic code and procedural model generation code, as well as importers/exporters for the 3d modeller Blender. So you kind of get my level of experience. So can anyone explain or link to a tutorial which explains what needs to be done, without advanced math or with mentioning what math concepts are needed?
This is what I want to achieve:
http://www.youtube.com/watch?v=dEipENLes10
http://www.dailymotion.com/video/xn3xfn_mercury-meltdown-psp-un-trailer-pour-mercury-meltdown_videogames?search_algo=2
Though with probably more metaballs on screen at the same time.

Yousa looking fora spicy metaball or a smootha metaball?

"The uploader has not made this video available in your country." That might just be because I'm at work and sometimes our stuff goes through India..., but consider the Indian users.

For what it's worth, it's also not available in the US, so the audience is rather severely limited... :P

http://www.dailymotion.com/video/xn3xfn_mercury-meltdown-psp-un-trailer-pour-mercury-meltdown_videogames?search_algo=2

Mercury was definitely using marching cubes to do its rendering (Although when the blobs were the size of a particle we just rendered a sphere).

One option is to use Marching Cubes. There are plenty of tutorials and example code in the Internet such as this. Implementing this is not very easy, but doable.
Thanks to the increased power of computers and especially GPUs, raycasting has also become a fast enough solution for rendering metaballs and other surfaces. Check for example this tutorial. This should be easier to implement. The downside is that it might not fit to the rest of the 3D engine as well as polygonizing the metaballs.

Unfortunately, 'without advanced math' is a fairly high bar to set for this particular tutorial, because the topic is inherently fairly advanced; metaballs are just a more colloquial way of talking about a particular type of isosurface visualization.  The simplest way to conceptualize it may be to imagine taking everything down a dimension; imagine that you're working on a plane (or technically the surface of a sphere) rather than in space, and consider a classic heightmap; then the coastline of the terrain represents one isosurface: it's the set of all the points on the map where the height (the elevation above sea level) is zero.  Now, suppose that you had a bunch of elevation data and you were asked to draw coastlines.  One approach would be to (somehow) find one spot along a coast and then 'follow that coastline' until you get back to your original point — but that requires you to find that first point, and when you complete your loop you can't be sure whether you've missed anything (imagine tracing the coast of England and entirely missing Ireland in the process).
Instead, you might try an approach where you scan over your map pixel by pixel, looking for spots where you have two adjacent points, one above water and one below, and then carefully drawing a line that cuts between the two, somehow making it match up from pixel to pixel.  The generalization of this idea from two to three dimensions is commonly known as the marching cubes method, and it's the most common algorithm for rendering isosurfaces; things are somewhat more complicated in the 3d case than in 2d (since you effectively have 256 cases, one for each of the 28 possible assignments of 'above surface' and 'below surface' to the vertices of a voxel), but the core ideas are the same.  Note that even pretty low resolutions on your grid can give good results for this; the demo you linked to is probably running the Marching Cubes algorithm on a 32x32x32 (or likely even 16x16x16) grid and it looks perfectly reasonable doing so.
This leaves open the question of just what your heightfield is, of course — I don't have time to go into that side of things right now (although some searching should find you a handful of different potential functions), but I'll try and flesh this answer out a bit later to give some of the details on that front too.
Of course, because you're essentially dealing with n3 pieces of data (the values on an n x n x n grid) then even fairly low grid resolutions can get expensive pretty fast.  With the right potential function, though, you can use interval arithmetic to bound the values of your potential function on larger chunks of space and cut down on the number of actual calculations you have to do; essentially, this is applying octree-style spatial partitioning to the metaball problem.

Correct me if I'm wrong, but Ireland's coastline isn't connected to England's coastline.

@Pharap That was exactly my point - if you're trying to get the coastline of all of the British Isles, then starting in e.g. Brighton and 'walking' the coast will miss an awful lot of it.  If you didn't know that there was another island you'd have no idea that you weren't done.

You said England's coastline, not the British Isles' coastline. England's coastline excludes Scotland, Wales and Ireland.

@Pharap Mea culpa; I'll try and revise the example - what I was trying to get at was that it was like trying to get all of the British Isles, but only getting England itself because that's where you started.  A slightly less complicated case might make things easier to grok. :/

It's understandable why you made the mistake, a lot of people (even the ones from England and other places in Britain) think England == Britain and use the two interchangeably. Normally you'd only end up upsetting the other residents of Britain who aren't English, but in this case it's more a matter of the analogy's correctness which is a far larger concern. Clean that up and I'll upvote, delete my comments and pretend it was always that way.

There is another quite impressive solution for this problem using GPU based raycasting approach together with Depth Peeling and Bezier Clipping algorithms.
Implementation is not straightforward but performance is worth it. Please check the white-paper.
Not sure if Python is good idea for such problem since is more related to shader programming.
If you still interesting we can collaborate together to solve this problem. I suggest to use tooling like Godot, Unity or Unreal

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Basic procedural generated content works, but how could I do the same in reverse?
My 2D world is made up of blocks. At the moment, I create a block and assign it a number between 1 and 4. The number assigned to the nth block is always the same (i.e if the player walks backwards or restarts the game.) and is generated in the function below.
(Image shows a small portion of the game, in practice there are much more blocks)

As shown here by this animation, the colours represent the number.
function generate_data(n)
    math.randomseed(n) -- resets the random so that the 'random' number for n is always the same
    math.random() -- fixes lua random bug
    local no = math.random(4)
    --print(no, n)
  return no
end

Now I want to limit the next block's number - a block of 1 will always have a block 2 after it, while block 2 will either have a block 1,2 or 3 after it, etc.
The next block's number is taken at random from the next table:

{
   [1] = {next = {2}},
   [2] = {next = {1,2,3}},
   [3] = {next = {4}},
   [4] = {next = {1,3,4}},
}

Before, all the blocks data was randomly generated, initially, and then saved. This data was then loaded and used instead of being randomly called. While working this way, I could specify what the next block would be easily and it would be saved for consistency.
I have now removed this saving/loading in favour of procedural generation as I realised that save whiles would get very big after travelling.
Back to the present. While travelling forward (to the right), it is easy to limit what the next blocks number will be. I can generate it at the same time as the other data.
The problem is when travelling backwards (to the left) I can not think of a way to load the previous block so that it is always the same.
Does anyone have any ideas on how I could sort this out?

When you say that a block can only have a block with a certain value after it do you then mean only in the left to right direction? Also, are the blocks in 2D or 1D as in the animation?

The block's value I am asking only applies when travelling to the right. The blocks only expand in the X axis, there is no Y transitioning.

You might skip the random component and use a deterministic pseudorandom generator, like 1D Perlin noise. Direction becomes irrelevant and you don't have to store anything.

My first thought was to calculate sort of a hash value for every block and use it as aseed to generate the same block every time but  I don't really see a way to do that when there is only a rule for transitioning from left to right. If you could change the ruleset to go in two directions somehow then it might be easier but I expect there's a reason behind your current scheme...

I want the world to be the same each time, the limiting rule would give me more control over the world

If I understand your question correctly you'd like that each block be random, but blocks beside each other are related. In terms of a game, the sequence of rooms is random, but neighbouring rooms have to be compatible in some way.  Going right isn't a problem since you have the current room and can easily apply the contsraint to the next room. Going left is a problem since you can't be certain which room was there.
Instead of trying to generate a specific block number instead think about the transitions between the blocks. Your random generator will produce a transition delta between the rooms.  The delta value for a given block will be random, but based on a fixed seed (thus constant for a particular game). You then apply this delta to the player's current room number to get the new block. If you are going right you add the delta, and if going left your subtract the delta.
That is, you are currently in Block X with a value of V. Let's say the left-delta of block X uses X as a seed and the right transitions uses X+1. To go right you calculate the transition of X+1 and add it to V. To go left you calculate the delta at X and subtract it from V.
An example with values, say the delta values are [ 0, 1, -1, 0 ].

You start at block 0, which we give value 4 (random number)
To walk right we get delta X+1 = 1
You are now at Block 1 with a value 4+1 = 5
Right again, Block 2 with a value 5-1 = 4
Right again, Block 3 with a value 4+0 = 4
Walk left, delta X = -1
You are now at Block 2 with a value 4-(-1) = 5
Left again, Block 1 with a value 5-1 = 4
Left again, Block 0 with a value 4-0 = 4

You can see that walking both left and right will result in the same value produced for each block.

The fixed seed idea is the way to go, but you can keep it very simple.
If you concern is the save game size, just save the seed for each level and re-generate it entirely at game startup, in you own fixed order (e.g. for a row of blocks, from -1000 to +1000).
Oh, and maybe this save game size isn't an issue after all. Think about how big the Minecraft world is, and I'm pretty sure at least a good part of it is saved:

This isn't really answering the question of how to determine room X-1, given a known room X, and the rules on adjacent rooms.

Well, at least I tried something more elaborated than YAGNI ;)


text:
OpenGL Learning Material (that's up to date)

Possible Duplicate:
What are some good learning resources for OpenGL?
Good resources for learning modern OpenGL (3.0 or later)?

So im sure there are topics on this, but alot of them list older material. And the last book:
http://www.amazon.com/OpenGL-SuperBible-Comprehensive-Tutorial-Reference/dp/0321712617/ref=sr_1_1?ie=UTF8&qid=1346116133&sr=8-1&keywords=opengl
REALLY REALLY disappointed me. I DO NOT want to use someone else's library to learn this stuff, that bothers me SOOO much.
So I was hoping there was a newer book that goes into detail, and doesn't use some sort of library "Hiding" everything from you.
Or should I just look at older material? If so....anything thats not "too" out of date. Terrain tutorials are a plus (that's kinda my "goal").
Thanks

This question has been asked plenty of times already.

There are very few.  Here are the only two I know of, one of which is still quite incomplete.
This first one is slowly becoming the "de facto" OpenGL tutorial.
http://www.arcsynthesis.org/gltut/
This second one is only several chapters in with no updates in a while, but hopefully if enough people pester the author he'll keep working on it.  I found the writing style to be pretty good for a technical topic.
http://openglbook.com/

http://meta.gamedev.stackexchange.com/questions/877/should-i-answer-questions-that-do-not-belong-here


text:
How to flip a BC6/BC7 texture?
I have some code to load DDS image files into OpenGL textures, and I'd like to extend it to support the BC6 and BC7 compressed formats introduced in D3D11. Since DirectX and OpenGL disagree about whether a texture's origin is in the upper-left or lower-left corner, my DDS loader flips each image's pixels along the Y axis before passing the pixels to OpenGL.
Flipping compressed textures presents an additional wrinkle: in addition to flipping each row of 4x4-pixel blocks, you also need to flip the pixels within each block. I found code here to flip BC1/BC2/BC3 blocks, and from the block diagrams on MSDN it was easy to adapt the BC3-flipping code to handle BC4 and BC5. The BC6 and BC7 formats look significantly more intimidating, though. Is there a similar bit-twiddling trick to flip these formats, or would I have to fully decompress and recompress each block?
UPDATE: It turns out the texture flip was only necessary because my texture coordinates were being incorrectly inverted at export time. Removing both flips made the code both simpler and faster (thanks Humus!). Flipping BC6/BC7 blocks may still be an interesting challenge, but it's no longer relevant to my original scenario.

Note that if you flip the texture coordinates instead of the texture images, you cannot use FBOs with the same meshes / shaders.

That is true. Leaving DDS textures unflipped also causes them to appear upside down in tools like gDEBugger. Hrm.

I suspect it is indeed possible to flip BC6-7 blocks with much less work than a full decompress and recompress, but it's still no picnic and is much more complex than flipping BC1-5 blocks.
First of all, BC6-7 have a variety of modes that can be selected per block.  The modes have completely different binary layouts, so you'd pretty much have to write a different flip routine for each mode (there are ~20 of them altogether, IIRC).
Another difficulty is the partitioned modes, where the pixels in the block are partitioned into 2 or 3 subsets, each with its own RGB line segment.  The partition must be chosen from a predefined set; the ones for BC6 can be seen here.  The problem is that this partition set is not symmetric under vertical flips.  However, I suspect it is symmetric under some combination of vertical flips and interchanging the two subsets.  For example, looking at the partition #22 (6th row, 3rd column) at that link, there is no vertically flipped version of it in the table, but if you vertically flip and interchange 0s and 1s, you end up with the partition #9 (3rd row, 2nd column).  I haven't verified that every partition can be flipped this way, nor have I checked the ones for BC7 (which also includes partitions with 3 subsets).
Even if that works, you're still not home free.  In BC1-5, the order of the two endpoints of the RGB line segment was used to switch modes, but in BC6-7 the order of endpoints is chosen to fix one bit of the per-pixel indices in each partition subset.  Therefore if you change the partition around you might also have to swap the order of endpoints.
And last but not least, in BC6-7 the endpoints are often delta-compressed (i.e. one endpoint is stored at full precision and the others are stored as lower-precision deltas from it).  Swapping partition subsets and endpoint order will switch which endpoint is the high-precision one, so you'll have to shuffle the low-precision bits around and negate some deltas.
All in all, it doesn't seem like there's any fundamental showstopper (though I haven't actually written the code), but it sure would be a lot of work to flip or rotate these formats.  If possible, I'd recommend flipping the images in your art pipeline before they get compressed.
(BTW, the fullest specification of BC6-7 I've found is the ARB_texture_compression_bptc spec; I also wrote a blog post about the BCn formats awhile back.)

Thanks; I am sufficiently terrified. I actually went searching for your blog post, but couldn't remember the link. It's an excellent resource on all things BCn; that alone is well worth an upvote!

The flipping is only a matter of default on the two formats.  You can go against the default.
This is probably better to do on the OpenGL side, because OpenGL is lower level, and thus less likely to lose optimization when doing things like this.


text:
Is it possible to update the livetile in XNA WP7 game?
( I'm not sure if this question belongs here, but since it is related to game development and I have no idea where else I should post this, I will post this here )
As the title says, what I am basically asking is if it is possible to update the livetile of an pure XNA game ( not SL + XNA hybrid )?
I've been thinking something like that whenever user launches the game, I would create an texture dynamically and then update the livetile to show that texture. Even better would be if I could schedule this code to run for example once a day, without requiring user to even launch the game.
Is this possible in WP7 or in WP8 ( is the WP8 SDK even publicly released yet? ) in pure XNA game? What about in XNA + SL hybrid?

What part of updating isn't working? If you add the Microsoft.Phone.Shell.ShellTile libraries/namespace and follow the standard tutorial (http://blogs.microsoft.co.il/blogs/pavely/archive/2011/09/30/dynamic-live-tiles-in-windows-phone-7.aspx) doesn't it work?

Also, the WP8 SDK has only been released yet to people who had WP7 apps on the market, but it will soon be made available to all.

@RoyT. Ahh, thanks. I was aware of Microsoft.Phone.Shell namespace, but I wasn't sure how it could be used since it required Uri of the image, but that article clarified what I have to do. I will update whether I succeed or not. However, I'd still like to know if it is possible to schedule the code that updates the tile to run on a regular basis, without user needing to launch the game. ShellTileSchedule-class doesn't seem to allow to run any code, but rather just wants Uri of the image.

I managed to update the tile using following code:
public static class ApplicationInfo
{
    public static ShellTile ApplicationLiveTile
    {
        get { return ShellTile.ActiveTiles.FirstOrDefault(); }
    }

    public static void UpdateTile(Texture2D texture)
    {
        const int TextureSize = 173;
        const string FilePath = "/Shared/ShellContent/tile.jpg";

        // Save texture to isolated storage
        IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
        using (IsolatedStorageFileStream stream = isolatedStorage.CreateFile(FilePath))
        {
            texture.SaveAsPng(stream, TextureSize, TextureSize);
        }

        // Update the tile
        ShellTile tile = ApplicationInfo.ApplicationLiveTile;
        if (tile != null)
        {
            tile.Update(new StandardTileData()
            {
                BackgroundImage = new Uri("isostore:" + FilePath, UriKind.Absolute),
            });
        }
    }
}

I haven't yet tried to make scheduled updating of the live tile as I described in the OP, but it possibly can be done by using Windows Phone Scheduled Task Agent.


text:
MarteEngine Tile Collision
I need to add collision to my tile map using MarteEngine. MarteEngine is built of of slick2D. Here's my tile generation code:
Code:
public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException
   {
      for (int x = 0; x < 16; x++) {
         for (int y = 0; y < 16; y++) {
            map[x][y] = AIR;
               air.draw(x * GameWorld.tilesize, y * GameWorld.tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 7; y < 8; y++) {
               map[x][y] = GRASS;
               grass.draw(x * tilesize, y * tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 8; y < 10; y++) {
            map[x][y] = DIRT;
               dirt.draw(x * tilesize, y * tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 10; y < 16; y++) {
            map[x][y] = STONE;
               stone.draw(x * tilesize, y * tilesize);
         }
      }
      super.render(gc, game, g);

   }

And one of my tile classes (they're all the same, the image names are just different):
Code:
package MarteEngine;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

import it.randomtower.engine.entity.Entity;

public class Grass extends Entity {

   public static Image grass = null;

   public Grass(float x, float y) throws SlickException {
      super(x, y);

       grass = new Image("res/grass.png");

       setHitBox(0, 0, 50, 50);

       addType(SOLID);
   }

}

I tried to do it like this:
Code:
for (int x = 0; x < 16; x++) {
         for (int y = 7; y < 8; y++) {
               map[x][y] = GRASS;
               Grass.grass.draw(x * tilesize, y * tilesize);
         }
      }

But it gave me a NullPointerException. No idea why, everything looks initialized right? I would be very grateful for some help!

This should be an easy problem for you to solve by stepping through the code with the debugger. Honestly once you learn to use the debugger you will feel silly for having asked this question :)

@Byte56 Haha probably will but is it really that obvious? Can you at least give me a hint to which class its in?

What line is the it saying the null pointer is on?

Oh, I don't know where the problem is. I'm just saying you could figure it out in way less time than it took you to write the question. With the debugger it really will be that obvious.

@GameDev-er it says on line 58 of GameWorld which is my tile generation. Line 56 starts at: [code]Air.air.draw(x * GameWorld.tilesize, y * GameWorld.tilesize);
[/code]

Overall, I think this question is too localized for the site. (This is typically the case with questions that are about code errors).

I agree. This seems like it should be migrated to SO.

From the code you posted it looks like you never actually call the constructor for Grass, so Grass.grass is still null. It never gets a new Image(...) assigned to it. If you try to call a method on a null object, you'll get a NullPointerException.
What are the values of AIR, GRASS, DIRT, and STONE? Are they global?
EDIT:
Where in your code do you call the constructor for Grass (or Air, Stone, or Dirt)?
Grass theGrass = new Grass(0, 0);

Yes, they are in my GameWorld Class, and are just public static ints representing nothing pretty much. The code that is causing the error is actually Grass.grass.draw(). grass is set to null. But then I call on it later with grass = new Image(). Is this the problem?

I think the problem is that the constructor for Grass is either 1) not called (leaving Grass.grass as null) or 2) called after the code that you posted above, so it hasn't initialized anything yet. I will update my answer with more information.

I call it in the Grass class with grass = new Image(res/grass.png); I realize this is not a constructor but all it is doing is setting an image. Then I call it with Air.air.draw(x * tilesize, y * tilesize);

I see that you instantiate the Grass.grass image in the Grass constructor, but that constructor never gets called, so the statement grass = new Image(res/grass.png); is never executed.

So how should I call it? I'm sorry, I'm really tired right now and its probably obvious but I just have no idea how to do it right now.

@opiop65 You need to invoke the Grass constructor at least once like the code near the end of my answer. Since you never call the constructor, the static data is never given a value other than null.


text:
How can I implement an Iris Wipe effect?
For those who doesn't know:

An iris wipe is a wipe that takes the shape of a growing or shrinking
  circle. It has been frequently used in animated short subjects, such
  as those in the Looney Tunes and Merrie Melodies cartoon series, to
  signify the end of a story. When used in this manner, the iris wipe
  may be centered around a certain focal point and may be used as a
  device for a "parting shot" joke, a fourth wall-breaching wink by a
  character, or other purposes.

Example from flasheff.com

Your answer may or may not include a coding sample, a language agnostic explanation is considered enough.

Further explanation for those unfamiliar: Animated gif of an iris wipe - note the wipe can open the next scene, or close the current scene (imagine it played in reverse).

I think you need to specify the implementation platform. What is usefully efficient will depend greatly on what graphics operations are available.

In a 2D iPhone game I played recently, iris wipe effect was simply done using full screen sprites with some transparency :

These pictures are simply draw over the screen once everything else have been draw (like hud, background, ...).
You can easily build theses pictures in photoshop, gimp, flash or whatever 2D program you have.

You can also do it "realtime", by using 2D primitives that are available in your framework (you dont specify any).
Here is an example in opengl (un-tested) :
void drawIris(float inner_radius)
{
   const float outer_radius = 300.0f; //something big enough to cover whole screen

   glBegin(GL_TRIANGLE_STRIP);
   for (int i = 0; i < 360; i++)
   {
      float degInRad = i * DEG2RAD;
      glVertex2f(cos(degInRad) * inner_radius, sin(degInRad) * inner_radius);
      glVertex2f(cos(degInRad) * outer_radius, sin(degInRad) * outer_radius);
   }
   glEnd();
}

//to change the way iris animation is done,
//you can replace this function by something else like smoothstep() function
float lerp(float a, float b, float t)
{
   return a * (1.0f - t) + b * t;
}

//usage :
drawIris(lerp(0.0f, 50.0f, time));

Here is how it works :

We draw a open circle with an outer radius bigger than the screen. Everything outside the screen will automatically be clipped by opengl. Inner radius is aperture size of iris.

Just to clarify, drawing one circle on top of the other 'subtract' the intersection area in this case?

No, we draw only once. Think of a unfilled circle with a huge border around (like a ring).

If I caught somebody on my team using the texture approach on iOS, I'd give them a stern talking-to.  That sort of large transparency would absolutely murder the frame rate on many of the devices (particularly the iPhone4 and iPad1).  But it's probably the best approach on desktop/console.

If using OpenGL or Direct3D, you can write a post-processing shader to do the job rather easily.
You'll be rendering a full-screen quad on top of the already rendered scene. The shader takes in (as a uniform) current radius of the iris (so you'll "animate" that on the CPU).
In the fragment/pixel shader, you'll get the current't pixel's screen coordinates from the interpolated vertex coordinates. You then calculate the distance to the center of the screen and output a black pixel if the distance is greater than the current iris radius, and a transparent one if not.
If you desire softer edges, you could look up vignette shader and animate its radius in the same way.

+1 for using pixel shaders (if available). That would make possibility of having smooth borders around iris easily.

Another approach would be to generate a 2d mesh that has a hole in the middle, and render that on top of everything else.
Generating this mesh may seem complicated at first, especially when the hole is partially bigger than the screen, but remember that the mesh may be way bigger than the screen.
I'd go with something like a huge "o" circle shape.
Alternatively, you can use stencil buffers to first render the parts that you want to keep visible to the stencil buffer and then render a huge quad over everything using said stencil buffer.


text:
Java 2D Tile Collision
I have been working on a way to do collision detection forever, and just can't figure it out. Here's my simple 2D array:
for (int x = 0; x < 16; x++) {
           for (int y = 0; y < 16; y++) {
              map[x][y] = AIR;
              if(map[x][y] == AIR) {
                 air.draw(x * tilesize, y * tilesize);

              }

           }
        }

    for (int x = 0; x < 16; x++) {
           for (int y = 6; y < 16; y++) {
              map[x][y] = GRASS;
              if(map[x][y] == GRASS) {
                 grass.draw(x * tilesize, y * tilesize);

              }

           }
        }
    for (int x = 0; x < 16; x++) {
           for (int y = 8; y < 16; y++) {
              map[x][y] = STONE;
              if(map[x][y] == STONE) {
                 stone.draw(x * tilesize, y * tilesize);
              }

           }
        }

I want to do it with rectangles, and using the intersect() method, but how would I go about adding rectangles to all the tiles?
Edit:
My player moves like this:
if(input.isKeyDown(Input.KEY_W))
    {
        shiftY -= delta * speed;
        idY = (int) shiftY;

        if(shift == true)
        {
            shiftY -= delta * runspeed;
        }

        if(isColliding == true)
        {
            shiftY += delta * speed;
        }
    }

    if(input.isKeyDown(Input.KEY_S))
    {
        shiftY += delta * speed;
        idY = (int) shiftY;

        if(shift == true)
        {
            shiftY += delta * runspeed;
        }

        if(isColliding == true)
        {
            shiftY -= delta * speed;
        }
    }

    if (input.isKeyDown(Input.KEY_A)) {
        steve = left;
        shiftX -= delta * speed;
        idX = (int) shiftX;

        if(shift == true)
        {
            shiftX -= delta * runspeed;
        }

        if(isColliding == true)
        {
            shiftX += delta * speed;
        }
    }

    if (input.isKeyDown(Input.KEY_D)) {
        steve = right;
        shiftX += delta * speed;
        idX = (int) shiftX;

        if(shift == true)
        {
            shiftX += delta * runspeed;
        }

        if(isColliding == true)
        {
            shiftX -= delta * speed;
        }
    }

(I have tried my own collision code, but its horrible. Doesn't work in the slightest)

I'm not sure if this is relevant to the question, but it may save you some confusion later. You seem to be setting map[x][y] and then checking the value immediately after, which is always going to be true.

Right, wasn't really worried about that, but I should probably change it shouldn't I?

Regarding your question, are you using a physics engine?

You need to be more precise. Please edit your questions and indicate which objects need to be tested for collisions. Collisions are are usually tested for moving objects. In your example nothing is moving...

I'm using Slick2D, so no. Could you recommend a good easy library that adds in collisions?

@opiop65 i edited your question to add slick2d tag. You should do so for your further slick2d related question :)

First, in your example you do:
if(isColliding == true)

Where isColliding is calculated?
An easy way to check for collision in a tiled environment is to check the tile facing the player e.g if the player wants to move up and if he's currently on tile x,y, you will check if the tile x,y-1 is a blocking tile (is not AIR in your case, i suppose).
The above method only works if the player have the size of the tiles and if the player move tile by tile, and it does not seem to be your case.
If your player has a totally different size than your tiles and/or can move more/less than TILE_SIZE per frame, you will need to use a bit more complex approach (also described here).
Basically, you need to create a new Shape for each of your game entities and keep them in a kind of Collection and each time your player move, proceed all the shapes in this collection and check if one of them intersect with your player's shape.
public Class CollisionSystem {

    public static List<Shape> collidingShapes = new...

    public static boolean checkPlayerCollision(Shape playerShape) {
        for (Shape s : collidingShapes) {
            if (s.intersects(playerShape) {
                 //or do some more precise collision calculation here, like pixel perfect
                 return true;
         }
         return false;
    }

It's a really simplified example since in a real case you will probably need to update position of the shapes for moving entities.

Wow, best and most simple answer I've found! Thanks!


text:
How do you ensure consistent experience across multiple graphics cards (or even driver versions)?
So I was writing a simple 2D game with OpenGL and SDL and had this problem when there was awful tearing when running in windowed mode (even though I explicitly asked SDL_SetVideoMode to use double buffering). Didn't worry about it all too much because most of the time the game grabs the entire screen, windowed mode is just for debugging.
Anyway, yesterday I updated my nVidia drivers and tearing disappeared, the game runs smooth and looks nice in windowed mode too. I can see how the problem may be in the graphics driver, but this leads to a question.
Obviously, professional game developers have to deal with a lot of different hardware/software configurations. What are the techniques they use to make sure the game looks the roughly the same on different graphics cards or even the same model of graphics card, but with different driver versions?

There are no techniques beyond keeping the differences in mind and always looking out for more (testing often on various hardware/software configurations).
As for the tearing problem, it's all about VSync. The driver update probably had it turned on by default. Double buffering is just the act of swapping buffers to avoid waiting while the display is redrawn. Tearing occurs exactly because the buffer swap occurs in the middle of the screen repaint operation.
To enable VSync in OpenGL, you need to use this extension in Windows, specifically the "wglSwapIntervalEXT" function, interval=1 would mean that buffer swap will wait for repainting of one frame, interval=2 means 2 frames etc. And interval=0 is the default "do not wait unless driver thinks differently" setting. Frame count per second equals your monitor's refresh rate setting.
X Window system (Linux, Mac) needs this extension.
P.S. You can also try SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1); Some say it doesn't work in windowed mode though.

This shouldn't be done programmatically -- it is a user setting (whether or not the user wants to have VSYNC on or not), you should probably respect the user's config settings.

It's possible (and highly suggested, just not in the answer above) to add an option to enable/disable VSync in the game. By the way, display driver control panels offer the possibility to override all application settings. So there's no harm done even if there's no such option added.

Stuff looks the same on different drivers due to DirectX and OpenGL.  That was the point of those API's, to abstract the graphics device from the programmer so he doesn't have to worry about it.
The tearing you see is likely your VSYNC setting, being set to OFF, and it's plausible that installing the new driver set it back to ON.

If your VSYNC setting was not set to synchronize the graphics device draw with the refresh interval, then tearing can occur.


text:
Partial Shader Signatures HLSL D3D11 C++
I had been debugging a problem I was having in a single shader file with 2 functions in it. I'm using DirectX 11, vs_5_0 and ps_5_0. I have stripped it down to its basic components to understand what was going wrong with the shaders, because the different named components of the Pixel and Vertex shaders were swapping the data being input:
void QuadVertex ( inout float4 position : SV_Position,
            inout float4 color : COLOR0,
            inout float2 tex : TEXCOORD0 ) {
    // ViewProject is a 4x4 matrix,
    // just included here to show the simple passthrough of the data
    position = mul(position, ViewProjection);
}

And a Pixel Shader:
float4 QuadPixel (  float4 color : COLOR0,
            float2 tex : TEXCOORD0 ) : SV_Target0 {
    // Color is filled with position data and tex is
        // filled with color values from the Vertex Shader
    return color;
}

The ID3D11InputLayout and associated C++ code correctly compiles the shaders and sets them up with some simple primitive data:
        data[0].Position.x = 0.0f * 210;
        data[0].Position.y = 1.0f * 160;
        data[0].Position.z = 0.0f;
        data[1].Position.x = 0.0f * 210;
        data[1].Position.y = 0.0f * 160;
        data[1].Position.z = 0.0f;
        data[2].Position.x = 1.0f * 210;
        data[2].Position.y = 1.0f * 160;
        data[2].Position.z = 0.0f;
        data[0].Colour = Colors::Red;
        data[1].Colour = Colors::Red;
        data[2].Colour = Colors::Red;
        data[0].Texture = Vector2::Zero;
        data[1].Texture = Vector2::Zero;
        data[2].Texture = Vector2::Zero;

When used with the shader, the float4 color always ended up with the position data, and the float2 tex always ended up with the color data. After a moment, I figured out that the shader's input and output signatures needed to be in the correct order and the correct format and be laid out in the exact order of the output from the Vertex Shader, regardless of the semantics:
float4 QuadPixel (  float4 pos : SV_Position,
            float4 color : COLOR0,
            float2 tex : TEXCOORD0 ) : SV_Target0 {

    return color;
}

After finding this out, My question is: Why don't the semantics map the appropriate components when going from Vertex Shader to Pixel Shader? Is there any way that I can make it so certain semantics are always mapped to other semantics, or do I always have to follow the rigid Shader Signature (in this case, Position, Color, and Texture) ?
As a side note for why I'm asking: I know that when using XNA, my shader signatures for functions could differ in position and even drop items from Vertex Shader to Pixel Shader function parameters, having only the COLOR0 and TEXCOORD0 components being used (and it would still match up correctly). However, I also know that XNA relied on DX9 (and maybe a little DX10) implementation, and that maybe this kind of flexibility no longer exists in DX11?

Yes, this behavior changed from DX9 to DX10+, don't know much about the real story behind it, but I suspect that DX9 had to remap registers between VS and PS at runtime anyway (when linking shaders) which is inefficient.
In DX10+, when you compile a VertexShader and a PixelShader, you can see which register will be affected to a particular semantic (see output of fx.exe compiler), and these registers (which will almost map to an hardware register) should match between the output of a stage to the input of the next stage. Note that the input of a stage could have less semantics mapped, as long as the order is the same and there is no gap in the mapping.
If you are using some legacy FX file (techniques/passes) with DX10+, the compiler will check input/output signatures for you. But if you are compiling separately VS and PS, you will have to double check any signature mismatch (or you can use D3DCompiler API to verify this yourself).
There is one exception for the input of the VertexShader that is coming from the VertexBuffer and the InputLayout. The InputLayout is able to specify the byte offsets of each vertex elements and how it maps to the semantic in the VS shader, so you can have a "sparsed" mapping, the input layout can have more vertex elements/semantic bindings than the VS input, as long as all semantics from the VS are covered by the InputLayout declaration. This is handy when you have a model that has several vertex elements, and want to use the same vertex buffers for several vertex shaders that are expecting different input layouts: you can map the layout of the vertex buffer to the layout of the vertex shaders (as long as the mapping is covering all the input of the VS shader).

BTW: in DX10+, the semantics are completely user-defined. Only the semantics starting with SV, like SV_Position, correspond to specific hardware registers. There is no meaning to COLOR0 or TEXCOORD0 anymore; you could just as well call them BACON and EGGS.  So of course when VS and PS are compiled separately it will not necessarily map the same semantics to the same registers.  But if you use the Effects 11 API and compile everything together as a technique, it will ensure matching semantics have matching registers.

Oh, yes, I forgot to mention the distinction between user-defined semantics and system semantics... but still, an input/output variable will be effectively affected to a register, no matter it is system or user-defined, and this register should match (same type/size) between the VS and PS.

Thanks for your help. I was really trying to figure out if there was a way to make it 'just map', but it probably is grossly inefficient on the shader-writing side. I'll just have to be conformant between VShader and PShader: the Vertex stuff I already know how to do, but thank you for writing out the idea here! I'm sure someone besides from me could benefit a ton from it.

thanks to @xoofx 's good answer, and I found this MSDN doc:
https://msdn.microsoft.com/en-us/library/windows/desktop/bb509650(v=vs.85).aspx


text:
jBullet Collision/Physics not working as expected
Below is the code for one of my objects in the game I am creating (yes although this is a cube, I am not making anything remotely like MineCraft), and my issue is I while the cube will display and is does follow the physics if the cube falls, it does not interact with any other objects in the game.  If I was to have multiple cubes in screen at once they all just sit there, or shoot off in all directions never stopping.  Anyway, I am new to jBullet, and any help would be appreciated.
    // Constructor
public Cube(float pX, float pY, float pZ, float pSize)  {
    posX = pX;
    posY = pY;
    posZ = pZ;
    size = pSize;
    rotX = 0;
    rotY = 0;
    rotZ = 0;

    // physics stuff
    fallMotionState = new DefaultMotionState(new Transform(new Matrix4f(new Quat4f(0, 0, 0, 1), new Vector3f(posX, posY, posZ), 1)));
    fallRigidBodyCI = new RigidBodyConstructionInfo(mass, fallMotionState, fallShape, fallInertia);
    fallRigidBody = new RigidBody(fallRigidBodyCI);
}

Welcome to GDSE. We're not fixing bugs, take a look at FAQ: http://gamedev.stackexchange.com/faq Stack Exchange is about solving repeatable problems. Please rephrase your question in the way it may in future show up in google for someone else having a similar problem. Changing title and replacing the code with a special case designed just to show the problem would be a good start.

Move fallShape.calculateLocalInertia(mass, fallInertia); to before you create RigidBodyConstructionInfo

I tried your recommendation msell, but everything still just kinda doesnt sit where they are coded to.  They just fly around..  I think my issue is on the below line, any ideas?
fallMotionState = new DefaultMotionState(new Transform(new Matrix4f(new Quat4f(0, 0, 0, 1), new Vector3f(posX, posY, posZ), 1)));

From the given code I cannot say what the problem could be. The following code is working fine for me.
First create the physics world:
// Create the physics world
BroadphaseInterface broadphase = new DbvtBroadphase();
CollisionConfiguration collisionConfiguration = new DefaultCollisionConfiguration();
Dispatcher dispatcher = new CollisionDispatcher(collisionConfiguration);
ConstraintSolver solver = new SequentialImpulseConstraintSolver();
DiscreteDynamicsWorld dynamicsWorld =
    new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
dynamicsWorld.setGravity(new Vector3f(0, gravity, 0));

Then create physics objects:
// Create a physics object (sphere)
MotionState motionState = new DefaultMotionState();
CollisionShape collisionShape = new SphereShape(radius);
Vector3f localInertia = new Vector3f(0, 0, 0);
collisionShape.calculateLocalInertia(mass, localInertia);
RigidBody rigidBody = new RigidBody(mass, motionState, collisionShape, localInertia);
rigidBody.setActivationState(CollisionObject.DISABLE_DEACTIVATION);
Transform transform = new Transform();
transform.origin.set(x, y, z);
rigidBody.setWorldTransform(transform);

And finally add the physics object to the physics world:
// Add the object to the world
dynamicsWorld.addRigidBody(rigidBody);

That helped out quite a bit, I like the activationstate disabling deactivation.


text:
Best way to Draw a cube for 3D Picking on a specific face
Currently I am drawing a cube for a game that I am making and the cube draw method is below.  My question is, what is the best way to draw a cube and to be able to easily find the face that the cursor is over?  My draw method works just fine, but I am getting ready to start to add picking (this will be used to mold the cubes into other shaps), and would like to know the best way to find a face of the cube.
public void  Draw() {
    // center point posX, posY, posZ
    float radius = size / 2;

    //top
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,0.0f,0.0f); // red
            glVertex3f(posX + radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY + radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //bottom
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,1.0f,0.0f); // ?? color
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();

    //right side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,0.0f,1.0f); // ?? color
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();

    //left side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,1.0f,1.0f); // ?? color
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //front side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,0.0f,1.0f); // blue
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //back side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,1.0f,0.0f); // green
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();
}

Your title doesn't match your question. I suggest changing it so it does.

made your recommended change to the title

It depends on how you implement picking. It may not matter how you draw it, because you won't be detecting a face that's been drawn already. Since it's already been sent to the graphics card, it's usually more work to get information back from the drawn image than just checking your objects directly.
If you implement picking in the way I've described here, you'll just be casting a ray and checking it against the objects in your game world to see if there's an intersection. So it will matter how you're storing your objects in your game world. For example, it's very useful if you can query your world to find objects at a specific location. If your objects were just stored in an array, you'd suffer O(N) time for determining if an object existed at a specific point.
As a side note. Just looking at your drawing code, you probably want to modernize that a bit. Direct drawing like that is very out of date. Look into VBOs.

You can at least update your drawing code so that all the vertices are surrounded by a single glBegin() and glEnd(). Same goes for popping and pushing matrices. OpenGL knows that 4 vertices makes a quad, you don't have to break them all apart like that.

I have always done it that way, but yeah I think I will try the way you are suggesting, it is cleaner.

Soo much cleaner and it works solid!

I like your idea of storing them by specific location, currently my game world is stored in a array of objects.  I will look into location based storage of objects.

I appreciate your help Byte56!


text:
Rotating a cube using jBullet collisions
How would one go about rotating/flipping a cube with the physics of jBullet?
Here is my Draw method for my cube object:
    public void  Draw() {
    // center point posX, posY, posZ
    float radius = .25f;//size / 2;

    glPushMatrix();
    glBegin(GL_QUADS);
        //top
        {
            glColor3f(5.0f,1.0f,5.0f); // white
            glVertex3f(posX + radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY + radius, posZ + radius);
        }

        //bottom
        {
            glColor3f(1.0f,1.0f,0.0f); // ?? color
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
        }

        //right side
        {
            glColor3f(1.0f,0.0f,1.0f); // ?? color
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }

        //left side
        {
            glColor3f(0.0f,1.0f,1.0f); // ?? color
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
        }

        //front side
        {
            glColor3f(0.0f,0.0f,1.0f); // blue
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
        }

        //back side
        {
            glColor3f(0.0f,1.0f,0.0f); // green
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();

}

This is my update method for the cube position:
    public void Update() {
    Transform trans = new Transform();
    cubeRigidBody.getMotionState().getWorldTransform(trans);

    posX = trans.origin.x;
    posY = trans.origin.y;
    posZ = trans.origin.z;

    Quat4f outRot = new Quat4f();
    trans.getRotation(outRot);
    rotX = outRot.x;
    rotY = outRot.y;
    rotZ = outRot.z;
    rotW = outRot.w;
}

I am assuming I need to use glrotatef, but it does not seem to work at all when I try that..
this is how I have tried to rotate the cubes:
    GL11.glRotatef(rotW, rotX, 0.0f, 0.0f);
    GL11.glRotatef(rotW, 0.0f, rotY, 0.0f);
    GL11.glRotatef(rotW, 0.0f, 0.0f, rotZ);

Here is how I am getting the XYZ for the cubes from jBullet:
    public void Update() {
    //cubeTransform = new Transform();
    cubeRigidBody.getMotionState().getWorldTransform(cubeTransform);

    posX = cubeTransform.origin.x;
    posY = cubeTransform.origin.y;
    posZ = cubeTransform.origin.z;

    processTransformMatrix(cubeTransform);
}

Remember that when using glRotate you need to rotate first then draw, then glRotate back to neutral. OpenGL rotate, translate and scale all set OpenGL into a state so that everything after that is drawn with that rotation, translation and scale.

that explains why everything was bouncing around oddly.. :/ blah

You are mixing quaternions with euler angles. You would need to do a conversion to make it work. Instead of rotations around specific axis, I recommend to use the transformation matrix from Bullet physics directly. This includes the position as well.
// These can be pre-allocated.
float[] matrix = new float[16];
Transform transform = new Transform();
FloatBuffer transformationBuffer = BufferUtils.createFloatBuffer(16);

// Get the transformation matrix from JBullet.
MotionState motionState = rigidBody.getMotionState();
motionState.getWorldTransform(transform);
transform.getOpenGLMatrix(matrix);

// Put the transformation matrix into a FloatBuffer.
transformBuffer.clear();
transformBuffer.put(transformation);
transformBuffer.flip();

GL11.glPushMatrix(); // Save the current OpenGL transformation
GL11.glMultMatrix(transformationBuffer); // Apply the object transformation
renderObject();
GL11.glPopMatrix(); // Restore the saved transformation

I really like this way of handling the rotations, but how would one go about reseting the glMultMatrix back to neutral?  I have tried a few methods such as: transformationBuffer.clear(); glMultMatrix(transformationBuffer);.  I have also tried to use transformationBuffer.reset();/transformationBuffer.rewind();

Here is what happens when I implemented the above: http://i1059.photobucket.com/albums/t428/superken81/aftermatrixflip.png

This is what the scene looks like prior to the above implementation: http://i1059.photobucket.com/albums/t428/superken81/beforematrixflip.png

Use GL11.glPushMatrix(); to save the matrix state and GL11.glPopMatrix(); to restore it after rendering the cube.

The screenshot looks like some scaling problem, no idea what is causing it. If that is the case, you could also create a matrix from a quaternion to get just the rotation matrix and use that for glMultMatrix. You also might need to transpose the matrix before passing to OpenGL, but I'm not sure about that.

Thanks msell!  I will look in transposing it, or investigating if it is a scaling issue.

no luck so far on trying to Transpose the matrix, but I am still looking.  it appears that OpenGl has a function for this, but it does not appear to yet be available in LWJGL that I have found.

just tried the following and I get the same result :(

GL11.glTranslatef(cubeTransform.origin.x, cubeTransform.origin.y, cubeTransform.origin.z);
GL11.glRotatef(cubeQuaternion.w, cubeQuaternion.x, cubeQuaternion.y, cubeQuaternion.z);

I also read that I should * 360 on the cubeQuaternion.w, which I also tried, and that made things slightly worse lol

Updated my answer to include the saving and restoring of the transformation matrix. Are the objects rotated correctly with the code above? Is the scaling the only issue you have with this? How are you creating the JBullet geometry for the cube?

i updated my question with how I am getting the xyz of the cubes from jBullet, hopefully that is what you are looking for.  I actually am already utilizing the push/popmatrix in my draw method, however I moved things around to be more like your code and still had the same results.

I really appreciate your help and I feel it is probably a minor thing, I just cant seem to see why everything is off.  This is my first venture into coding with jBullet and it has been quite frustrating at times, but I am not going to give up.

My suggestion is to not get the positions at all from JBullet. Instead just use the getOpenGLMatrix, which gives you both position and orientation. Then my other question is what parameters are you passing to the constructor of BoxShape? Do they match with vertices you are creating? Would everything work correctly if you just scaled the visuals by 2?

I actually do get them from the getOpenGLMatrix:
cubeRigidBody.getMotionState().getWorldTransform(cubeTransform);
posX = cubeTransform.origin.x;
posY = cubeTransform.origin.y;
posZ = cubeTransform.origin.z;

Sorry I forgot to mention I am also already scaling by 2.

Currently the constructor is passed the XYZ from a loop that I do to create the test enviroment.

Cube arrayCube = new Cube(blockX, blockHeight, blockY, .5f);
game_objects.add(arrayCube);
world.addObject(arrayCube.getCubeRigidBody());

The given code should be enough for generic JBullet rendering with LWJGL. For more complete example code check the demo application within JBullet, especially GLShapeDrawer.drawOpenGL() and LwjglGL.drawCube().

I think the issue was that I was setting the location in my Draw method, I am going to change things up and I will let you know if that was the issue.  Thanks for your help msell!

that was it, your code above worked great when I removed the stuff I was doing to get the xyz!  Thanks Msell

Please use a chatroom for extended discussion.


text:
Draw Rectangle To All Dimensions of Image
I have some rudimentary collision code:
public class Collision {
    static boolean isColliding = false;
    static Rectangle player;
    static Rectangle female;

    public static void collision(){
        Rectangle player = Game.Playerbounds();
        Rectangle female = Game.Femalebounds();

        if(player.intersects(female)){
            isColliding = true;
        }else{
            isColliding = false;
        }
    }
}

And this is the rectangle code:
public static Rectangle Playerbounds() {
    return(new Rectangle(posX, posY, 25, 25));
}

public static Rectangle Femalebounds() {
    return(new Rectangle(femaleX, femaleY, 25, 25));
}

My InputHandling class:
public static void movePlayer(GameContainer gc, int delta){
    Input input = gc.getInput();

    if(input.isKeyDown(input.KEY_W)){
        Game.posY -= walkSpeed * delta;
        walkUp = true;

        if(Collision.isColliding == true){
            Game.posY += walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_S)){
        Game.posY += walkSpeed * delta;
        walkDown = true;

        if(Collision.isColliding == true){
            Game.posY -= walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_D)){
        Game.posX += walkSpeed * delta;
        walkRight = true;

        if(Collision.isColliding == true){
            Game.posX -= walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_A)){
        Game.posX -= walkSpeed * delta;
        walkLeft = true;

        if(Collision.isColliding == true){
            Game.posX += walkSpeed * delta;
        }
    }
}

The code works partially. Only the right and top side of the images collide. How do I correct the rectangle so it will draw on all sides?

"How do I correct the rectangle so it will draw on all sides?" you mean "collide on all sides"? Also are you sure the position the position of the rectangle you create is the same as the entity position?

Oh yeah it should be collide sorry. And yes I'm sure. That doesn't cause any problems so I haven't changed it.

It would be interesting to see what you do when you know a collision happen. You only show the collision detection.

Oh sorry, I'll update the code to include my inputHandling class.

//This checks overlap in a single dimension -- either x or in y
public boolean checkOverlap(int start0, int end0, int start1, int end1)
{
    if(start0 > start1 && start0 < end1)
        return true;
    if(start1 > start0 && start1 < end0)
        return true;
    return false;
}

//This does it for two dimensions. If overlapping in X AND Y, you've collided.
//You can call this in your movePlayer handler, but if the "females" (er!) move
//AS WELL, then you must do it per update or you will miss collisions (unless
//you make sure all "females" are moved before the player, on each update).
public bool isColliding(Rectangle rect0, Rectangle rect1)
{
    if (checkOverlap(rect0.x, rect0.x + rect0.width, rect1.x, rect1.x + rect1.width) &&
        checkOverlap(rect0.y, rect0.y + rect0.height, rect1.y, rect1.y + rect1.height))
    {
        //resolve your collision. You don't need to store isColliding -- just
        //calculate, then act on the result.
    }
}

On each game loop update: Get your inputs, move the player, get all inputs for other entities and move them, then at the end, run through the full entities list (player + "females") and run isColliding() on each. This the standard way to do 2D AABB collisions.
Actually if you are running through the full list of n entities and comparing them against n-1 other entities, then for the first entity in the list, call it a, you will have to check against b through n, but on checking b you will not have to check it against a (since a was just checked against b in the prior step) or itself, so you would check from c through n... and so on for each remaining entity. This essentially looks like:
for (int i = 0; i < entities.length; i++) //run through ALL entities
{
   Entity e1 = entities[i];
   for (int j = i+1; j < entities.length; j++) //run through each entity AFTER e1
   {
       Entity e2 = entities[j];
       if (isColliding(e1.rect, e2.rect))
           resolveCollisionFor(e1, e2);
   }
}

@opiop65 Any luck?

@opiop65, If I helped, then you may as well accept my answer since your accept rating will improve and others will then be more likely to answer your questions in future -- thanks.

Looking at your code I think you forgot calling Collision.collision(); before checking if Collision.isColliding == true so Collision.isColliding has always the same value
You should do something like this:
if(input.isKeyDown(input.KEY_W)){
    Game.posY -= walkSpeed * delta;
    walkUp = true;
    Collision.collision();
    if(Collision.isColliding == true){
        Game.posY += walkSpeed * delta;
    }
}

Thanks, this will probably help later on but it still doesn't fix anything. The boolean updates correctly and is false when not colliding so thats not the problem...

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
ArrayList of Entites Random Movement
I have an arraylist of entites that I want to move randomly. No matter what I do, they won't move. Here is my female class:
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.Random;

import javax.swing.ImageIcon;

public class Female extends Entity {
static int femaleX = 0;
static int femaleY = 0;
double walkSpeed = .1f;
Random rand = new Random();
int random;
int dir;

Player player;

public Female(int posX, int posY) {
    super(posX, posY);

}

public void update() {
    posX += femaleX;
    posY += femaleY;

}

public void draw(Graphics2D g2d) {
    g2d.drawImage(getFemaleImg(), posX, posY, null);
    if (Player.showBounds == true) {
        g2d.draw(getBounds());
    }
}

public Image getFemaleImg() {
    ImageIcon ic = new ImageIcon("res/female.png");
    return ic.getImage();
}

public Rectangle getBounds() {
    return new Rectangle(posX, posY, getFemaleImg().getHeight(null),
            getFemaleImg().getWidth(null));
}

public void moveFemale() {
    random = rand.nextInt(3);
    System.out.println(random);

    if (random == 0) {
        dir = 0;
        posX -= (int) walkSpeed;
    }
}

}

And here is how I update the female class in the main class:
public void actionPerformed(ActionEvent ae) {
    player.update();

    for(int i = 0; i < females.size(); i++){
        Female tempFemale = females.get(i);
        tempFemale.update();
    }
    repaint();
}

If I do something like this(in the female update method):
public void update() {
    posX += femaleX;
    posY += femaleY;

    posX -= walkSpeed;

}

The characters move with no problem. Why is this?

Dude, what's with the females? Are you objectifying them? That's a danger zone!

-__- thanks for your help.. they were just part of a game!

Because (prior to your fix) that's exactly what you've asked it to do. Nowhere do I see femaleX or femaleY being updated; thus, they remain zero, and thus you add zero to the current position, so nothing moves.
I think you are not clear on what your code is supposed to be doing, here is how this is always meant to be approached:
//acceleration
float ax = 0;
float ay = 0;
//speed
float sx = 0;
float sy = 0;
//displacment AKA position
float x = 0;
float y = 0;

...

void update(...)
{
    //after all input and AI, etc. etc., finalise your physics
    //using the basic Equations of Motion a la Isaac Newton:
    //new velocity is old velocity plus current acceleration (usually derived from inputs)
    sx += ax;
    sy += ay;
    //new position is old position plus current speed
    x += sx;
    y += sy;
}

Whereas in your code, it almost seems as if you are saying position = position + someOtherPosition, which cannot really work. Speed (or as a vector, velocity) is the diff you apply to displacement, just as acceleration is the diff you apply to speed.
PS. Using acceleration is completely up to you -- you can just set velocities in your input handler code if you like. Many games do not need acceleration.

You cast walkSpeed to an int before adding it to the position in moveFemale(), its value will be 0 so nothing changes.

You have to call moveFemale(); in the update-method.

Information about why this is a problem and how this solves it makes for a better answer.