Hacker News new | past | comments | ask | show | jobs | submit login
How Do Bullets Work in Video Games? (gamasutra.com)
566 points by jger15 on Dec 25, 2019 | hide | past | favorite | 221 comments

Fun side note to this: although bullet collisions are trivial, sword collisions are genuinely computationally complex, in the sense that I’m not aware of a single publicly available game engine that ships with a robust real-time solver for sword-sword collisions.

I find this really interesting because it’s a complete inversion of reality, where bullet impacts are vastly more energetic and chaotic than sword clashes. It tells you something about the scale we play games at, maybe.

I don’t see people talking about it, but this has to be a huge part of why sword combat in video games is so much less explored and well-realized than gunfighting. Figuring out why it’s such a hard problem, and exploring the various workarounds and their limitations, is a fun weekend project if you know a little computational geometry. (And it’s probably the work of a few minutes if you know enough formal geometry, I guess.)

The great lie that games tend to run with is that if they define a sufficiently large lookup table of results, they get a convincing effect without being accurate to any form of reality.

This is basically true with almost all character controller behaviors(perfect ability to jump high, sidestep, slide etc. without stumbling) and also with combat results(add enough animations and you have a melee combat system; turn granular physical reactions like bullet impacts into a state change making the target "hurt" or "stunned"). And it's even true of the earliest ball-and-bat games: reduce hitting a ball to a lookup table of trajectories and you get Pong without having any trigonometry in your algorithm. You can define a massive swathe of gameplay code as combinations of "lookup table, finite state, timers, resource counters".

This is also true of the physics solvers: define the solver in terms of eliminating all the visibly wrong results(which in the base case means filtering the set of results that contain penetration), and you have one sufficiently good for gameplay. For 2D games this has classically meant solving AABB-AABB movements along 1 axis at a time(i.e. if your raycast is diagonal it's reduced to two one dimensional on-axis movements, which is trivial to compute). Once you want realistic physics as a "special effect" you typically will switch towards using a physics library to provide both solver and colliders, and so as a gameplay programmer you may never have to learn the physics problem in much depth.

The video games that really work with physics instead of against them are kind of exceptional, and tend to be categorized as "simulators" - flight sim, racing sim, pool sim, pinball sim. Or they are joke games like QWOP, or at their most fantastic, space games. When we actually simulate anything, the scenario-and-story space tends to reduce dramatically as everything starts converging around the sim's chaos. As we eliminate the sim, more can exist in the designer-fiat space. That's how we can have games about wrestling and swordfighting and yet not really be able to convey the physics or controls of those activities.

The problem with sword combat isn't the computational complexity, but the fact that reporting a hit late is much more noticeable.

If you are running across some open space and a bullet hits you, the game can report you being hit 500ms later and it's perfectly fine. With sword, the player can actually see the sword hitting and it has to report the damage at the same moment.

A game can compensate by having slower strike animations and preventing players to redirect sword mid hit. Dark Souls 3 does a pretty decent job there - once you press the attack button, you commit to a the attack animation and cannot change or cancel it. So, the receiving end can speed up the attack animation somewhat to compensate and show the sword hit approximately at the same time it hits "on the server". As long as you have good ping, the game feels close to real time - except that opponent attack animations feel somewhat faster than your own (so, harder to dodge and parry).

Appreciate the comment, but I want stress that the problem really is the computational complexity. (Or at least, computational complexity really is a serious problem.)

If everything in your world behaves like a bullet, physics is simple. If everything in your world behaves like a sword, physics is a nightmare. A lot of games with swords literally pretend that swords are made of bullets to get around this. No kidding.

To spoil my deep explanation: in the sense games are concerned with, a bullet is a non-rotating length-0 inertially-controlled sword. That doesn’t generalize cheaply.

Swords can be modelled as "oriented bounding boxes" or OBBs. OBB/OBB collision has been part of the toolkit for years and is not computationally complex. The computation of sword/sword collision is not the hard part. The gameplay mechanics to make it fun, are.

Actually no. Thin, quickly rotating objects are an area where a lot of collision detections libraries fall down - the simpler algorithms just look at the position of the objects each frame, and two swords can easily pass through each other in the time between frames.

The problem is called tunelling, and though there are some features to deal with it, there aren't any ones that are simple, reliable and cheap.

Why wouldn't the blended ray+physics technique described in the article not work? I am imagining projecting a bunch of rays from the blade along the vector of travel each physics tick and using that to determine if a collision will occur during that tick.

I've never tried to implement anything like that, so I am curious where that might Fail.

Spitballing here.

Model a sword as a point of rotation e, (elbow, shoulder, whatever, have the animator figure it out) location of the tip point p, and the linear velocity vector v of its tip. Look at the letter 'F': The elbow is the point at the bottom, the travel of the tip is the top bar, the travel of the hilt (not modeled) is the shorter bottom bar. The travel of the tip is the parametric equation `tv + p`, which defines the line `(tv+p)d + e` You have one line for each sword. Solve for the intersection of the two lines. If t is outside the bounds of your framestep, they do not intersect. Do basic comparisons on the length of the arm/forearm + sword length to figure out if they connect. Bonus: gives you one character slashing the others' wrists for free.

Piercing attacks are just hitscan.

If you really need to model elbows that are moving (probably only for characters on horseback while galloping) you'll need to parameterize the elbow point. Use the character's velocity vector I guess; I wouldn't do anything more complicated than that. I suppose that also works for combination slashing/thrusting attacks?

I'm too lazy to plug that into the line intersection formula, but it seems like a fairly basic linear algebra problem. Unless you're trying to make it super hyper realistic, (don't do that) I don't understand why the computational complexity is a problem.

That’s very complex compared to a model I was thinking about while reading this article.

Consider that many forms of sword fighting remove the complexity by creating zones. I’ve been told that a skilled swordsman can identify 16-32 zones considering where an attack can come from or where to strike.

Isn’t this a much easier model if you factor in the weight/mass/velocity of each particular character? This would be a little like auto-aim but you could still compute each path and create effects against one when they happen or not.


If you have 4-8 static blocks vs 16-32 attacks that would be fine, but if you need to calculate what happens when 16-32 attacks run into the same 16-32 attacks you have a combinatorial explosion problem which you then need to simplify.

One of the reasons I like going straight to the linear algebra approach is that you do a batch of basic arithmetic which the CPU does quite fast without branching, and then you do one branch to determine hit vs not-hit. Pairing zones with zones sounds like nested if/else statements, but I hadn't dived into considering that approach.

Here is the maths for rotation of vectors around arbitrary axes:


I've used these to simulate polymer growth branching in 3D. Determining if and where two lines in 3D space intersect requires determining the scalar parametric equations of the two lines, then solving 3 simultaneous equations using a method like gaussian elimination. Seems like the last step could be computationally taxing for a cpu if performed each time-tic during sword swings - not sure if modern GPUs are optimized for just this sort of problem.

I'm aware. I deal with rotations and intersecting geometries at work too.

There's a closed form 3x3 matrix inversion procedure which is very fast on CPUs. [1] We don't use it with pen and paper because it's too hard to remember and there's a lot of places to fuck up substitutions, but computers don't have problems with remembering obtuse formulas. (it's like the 2x2 inverse where you shuffle stuff around and divide by the determinant) So you're looking at about 60 instructions (one division operation) with no branching to solve Ax = b in R3. [2] The reciprocal throughput is 16.5 cycles, so 5.5ns on a 3GHz Skylake assuming everything's in cache. In gamedev you'll use an approximate reciprocal instead of the division, so the latency will be lower but AFAIK the throughput will be the same.

The slow part of rotations is actually computing the sin/cos of the angles. You'll notice my model avoids anything to do with angles: there are no transcendental functions. This is non-physical for a few reasons, notably it's not possible to swing a sword more than 90 degrees in one frame. It's fine for a video game where you assume a full sword swing will take 15-30 frames and good enough is good enough, but it's not fine for scientific computing. Video games are all about faking it when nobody's looking.

Also, my model starts with defining motion in terms of the scalar parametric equations of the lines. I did think about this before posting. :)

[1] https://en.wikipedia.org/wiki/Invertible_matrix#Inversion_of...

[2] https://godbolt.org/z/ND6tTM

You sure did think about it, hah, thanks for sharing!

What's the difference from a fighting game like sf2, where your legs and fist act as essentially the same thing as a sword. Dhalsim has some pretty long feet and arms in that game.

Fighting games like SF2 usually work on 2D hit boxes. [1] You have boxes which are defined as things that do hitting, boxes which are defined as areas that can get hit, and boxes that define clipping. If a do-hitting box overlaps a get-hit box, a hit occurs. It's a simple, elegant system that's ideal for a game with a fixed 2D playworld and fixed 2D attacks. It doesn't work for a system with free form 3D sword combat. If you block up and to the right, and a sword comes in from up and to the right, you should block it, but if it comes from up and to the left you should get hit.


Bullets don't have bullet/bullet collisions and they largely don't affect the player model at all.

Swords can hit other swords but they also have to convincingly portray the arms, head, torso and legs during any swing or interrupt.

Having said all that, I think Jedi Knight 2 is still the best swordplay system. But only because the animations just ignore everything in their way, as a lightsaber would. Each time lightsabers hit there'e either a brief flash of light or a power struggle.

> Having said all that, I think Jedi Knight 2 is still the best swordplay system. But only because the animations just ignore everything in their way, as a lightsaber would. Each time lightsabers hit there'e either a brief flash of light or a power struggle.

Agreed, but only if you put the following in your autoexec.cfg:

    seta helpUsObi "1"
    seta ui_iscensored "0"
    seta g_saberRealisticCombat "1"
    seta g_dismemberProbabilities "1"

While you're at it, bind a stormtrooper spawn to a key too. If you hold it down while your lightsaber is out, you get a whole pile of stormtrooper parts with these options on.

Nothing pushed my GeForce 2 harder than that pile of stormtrooper parts.

Offtopic: One day I'd like to see a game that simulates/emulates the multiple layers that go to make up a human character.

So you'd start with the skeleton, layer muscles on top of it, then fat layers, then skin. On top of that would come a couple of layers of cloth, then leather, mail, and plate armour.

My desire to see this has kind of sprung from mods for games like Skyrim, Fallout: New Vegas, and Fallout 4. Seeing the creativity of modders who make these amazing outfits, armours, and weapons, and wondering how they'd look if they were a single layer on top of other clothing.

This, combined with the amazing hitbox work that goes into some games, could be very cool to see. Imagine a character getting hit by an arrow: it would have a vastly different effect whether it hits on a shield, against shoulder armour, or against a helmet. Now imagine if the character had their arms raised for an overhead strike with a sword, and the arrow hit their side or under their arm?

>Offtopic: One day I'd like to see a game that simulates/emulates the multiple layers that go to make up a human character. So you'd start with the skeleton, layer muscles on top of it, then fat layers, then skin. On top of that would come a couple of layers of cloth, then leather, mail, and plate armour.

This is exactly how dwarf fortress works. It's not a flawless system though and it tends to make combat realistically brutal. You can even modify the raws to a pretty large extent and create your own creatures and beings made out of and up of pretty much anything.


I had no idea, that's very cool.

I’ve had this thought. You know what I worry, though— even if I did have a vividly realized simulation of a human body accurate enough to engage in realistic medieval melee combat, wouldn’t I just have her sit at home and write esoteric computer programs? That’s what I do with this one.

>That’s what I do with this one.

Having an infinite supply of them would effect your decisions.

Swords are also hard to control with a mouse and keyboard.

Imagine yourself surrounded by a transparent sphere, on which you can paint a point and a line. Where on the sword is that point? How does the point/sword travel along a line?

This is not easy to solve. What happens if you shift your perspective after a sword attack is drawn? Can you amplify it by looking away? Can you arrest the motion, by looking towards the executed sword motion.

(mumble) Nintendo Wii (mumble)

Modern VR motion controls are better. Much of the innovation in physics based gameplay and things like sword mechanics is happening in VR, because the controls are accurate, expressive and low latency. Wii had the idea but lacked real tracking (a smartphone accelerometer can do Wii gameplay better than Wii).

Even the improved Wiimote Plus?

VR controls are exausting, almost like a real sword battle. Real innovation for gaming is when the controls do not exaust you. What may look like a working system (touch-control) either vannishes after a while (novelty factor wears off) or turns into yet another stone held in a relaxed lapgrip..

(Mumble) Clang (mumble)

Do you happen to know what kind of tech Mordhau uses? Its not perfect but the hit detection seems far better than any other melee combat game I've tried.

I don’t know specifically, but the general trick is to get your approximate solve to have the impact happen at a consistent time, since that’s what players have fine-grained control over. Other stuff involved in restitution, like angle of deflection and force at the point of impact, you can basically fudge to be close enough for gameplay purposes. If a game feels really satisfying, it generally means that stuff has been tuned really carefully. (So it is with games.)

You work that stuff out with numerical accuracy if you can be careful about when you need to, but since the animations and audio cues need to be carefully tuned anyway, it tends to add unnecessary complexity.

Mordhau uses a lot of raycasts.

>sword collisions are genuinely computationally complex

Have you played Dark souls and or Sekiro? I've always been a little curious how FROM accomplishes such a great experience with melee weapons.

Also a shout out to Mordhau for similar reasons but with LOTs more people to worry about in a server.

I haven't played Sekiro but Dark Souls doesn't really model swords colliding at all. It just plays the animation and allows for the occasional interrupt, like when your sword hand is too near a wall. Your sword slices straight through the enemies and plays a sound effect depending on the hit.

But one of the reasons Dark Souls and Demon's Souls feel 'tough but fair' is that the animations are very explicit and mostly uninterruptible by the player. It meant if you made a mistake, it was probably your fault and not the animation or game logic.

Demon's Souls actually looked kind of cheap and had janky transitions at the time because of it but the games since then have been getting better at animating transitions between moves.

The animation-above-all-else style also leads to some silly interactions with the Havoc physics engine. For example, when you kick through a dead body the rag doll physics accelerate at the speed of the animated player leg causing it to look weightless and kind of ridiculous.

>Dark Souls doesn't really model swords colliding at all.

This is a good point, the only collisions are what you said and animations for parry windows.

And yes the rag doll physics in DS games is pretty silly.

Have you checked out Mordhau at all? Because that is probably more of the collisions/interactions you were initially referring to.

>Dark Souls doesn't really model swords colliding at all.

Does this really make a difference? There's nothing fundamentally different about sword to sword vs sword to body is there?

The anim set makes hits look good even though the impact is not physically calculated for collision angles and impact velocity and such. Perhaps you mean model in this way? Even still, the game has to at least do a hit detection on a deforming hitbox.

Do you happen to know how From accomplishes their hitbox animation and collision detection?

A lot of difference.

Real swords slide, slow down to a stop, jump back, get stuck, and variously swivel and yaw in your hands as they meet obstacles.

This is rather expensive to physically model, even harder to nicely animate, and nigh impossible to map to the keyboard and mouse controller combo.

The game itself would also probably become less predictable and less fun as a consequence.

There was a cool talk called "Phase-Functioned Neural Network for Character Control" that used a neural network to join animations together based on user input: https://www.youtube.com/watch?v=Ul0Gilv5wvY

Something like this where the gameplay outcomes smoothly animate realistic swordplay might be pretty fun.

Edit: For anyone wondering what truly accurate physics might do to gameplay, the Totally Accurate Battle Simulator is free on the Epic Game Store for Dec 26: https://www.epicgames.com/store/en-US/product/totally-accura...

It doesn't make sense to me that it would be expensive to model. It's just four line segments.

The math seems like it would be preposterously difficult. I wouldn't even know where to begin. Seems like a very serious algebra problem. But once you solve the equations I can't imagine it's more than a few matrix operations each frame.

But it's entirely possible I'm missing something that makes it unsolvable without discrete math that pushes it into the computationally costly realm.

I've toyed with this idea for a bit but gave up because it's difficult to make it feel like you're in control of the action due to the randomness it adds to simply hitting something.

The physics itself is not computationally complex as far as I know, but it depends on the amount of detail you want to simulate.

I personally think realistic systems like this are fun to make but they can often be frustrating when put in a game.

There's an old game called Die by the Sword released in 1998 which lets you control the movement of melee weapons with your


The gameplay feels kinda silly, but it works in this game because it doesn't take itself too seriously.

There is a game that does this. Exanima by Bare Mettle Entertainment. This is my first time with an account here, and I felt compelled to post this.

> Fun side note to this: although bullet collisions are trivial, sword collisions are genuinely computationally complex, in the sense that I’m not aware of a single publicly available game engine that ships with a robust real-time solver for sword-sword collisions.

That's not a sense in which you can determine the computational complexity of the problem. Perhaps accurate sword combat just isn't very fun. Maybe it makes convincing animation much harder. Maybe it makes controlling the character much harder. Maybe you just don't know that many games. There are plenty reasons that it might be true that no games that you know of shipped with a robust real-time solver for sword-sword collisions other than computational complexity.

> I find this really interesting because it’s a complete inversion of reality, where bullet impacts are vastly more energetic and chaotic than sword clashes. It tells you something about the scale we play games at, maybe.

Of course the modelling of bullets is also usually extremely simplified in video games. If there is anything we can learn from this I think it's that players prefer games to be predictable and controllable over them being perfectly realistic.

I prototyped a physical first person sword fighter doohicky once, so allow me to weigh in:

You're both right! I'd point out four big categories of difficulty:

1) Physics. You need a swept collision test capable of handling very high linear and angular velocity of very thin shapes (a sword is not thick, and the tip can move pretty dang fast), and collision response capable of dealing with the results. This is doable- conservative advancement operating on distance functions will work- but working out all the details in a way that makes the final result fast is not easy. A speedy implementation alongside a speculative contact solver can work, though: https://www.youtube.com/watch?v=sfgC_eNx9M8#t=1m20s

2) User interface. A mouse and keyboard struggle to express all the degrees of freedom available to a physical handheld weapon. Swinging using the mouse works okay, but you need to do so in a way that doesn't interfere with camera control, and you need to be able to interrupt and redirect movements at any point, then add jabs, different guards, ... Expressing all of that in a single intuitive interface that doesn't require awkward mode switching is not easy. My prototype had an okay-ish approach, and I think it could still be improved further, but there's no way a mouse-keyboard user would be able to compete with someone of equal skill using VR hand controllers. There's a good reason why melee combat games are so much more common in VR.

3) Graphics. Single planar projections simply aren't enough for first person (especially outside of VR)- it feels like wearing blinders. Even third person doesn't help enough, and seeing your character gets in the way of seeing your weapon and opponent sometimes. Using a nonplanar projection like stereographic fisheye, it starts feeling okay around 160 degrees, though 200+ is nice once you adapt to the mild distortion it introduces. This requires a pretty different approach to rendering (like multiple subviews, direct projection raytracing, vertex warped rasterization, etc.). A couple of examples: https://www.youtube.com/watch?v=jQOJ3yCK8pI https://www.youtube.com/watch?v=mIax_ProQ8c#t=1m4s

4) Animation. While achieving a level of animation quality common in early 2000's titles is pretty easy- just have a set of poses for various weapon states to interpolate between, blend in some leg motion, shrug, done- achieving a very high animation quality bar is extremely difficult. Most modern AAA games use massive libraries of mocap data, and in some cases the animations directly drive motion to make everything grounded and solid. For Honor is a good example: https://www.youtube.com/watch?v=4pdcA3mhe0E. But in a game allowing total physical control with expectation of proper physical response to every interaction, the mocap coverage requirements explode. You can still do pretty well if you have enough data and put in a huge amount of effort, but at a certain point you start wishing the magical machine learning genie would swoop in and save you.

I think all of these things are solvable enough to permit the existence of a game, but they're hard enough that it's not surprising that they are still so rare.

Just to close the circuit. If you do ever make the move to VR, frame times go way down and arc accuracy requirements for the very tip of the blade go way up. You are going to get really frustrated that you can’t just google up a numerically robust solver :)

In VR you will run into edge cases where the difference between a miss and a parry at the tip of the blade requires sub-frame rotational resolution at the controller. If it were a gun, you’d never know the difference— with a sword you can feel that it moves wrong during the frame. I don’t think there’s going to be any software solution for that, we just need better tracking hardware before we can properly model a 1-meter object held out at arm’s length.

Which makes you think about constraints, is all I’m saying.

On the software side of things, the good news is that the combination of a decent conservative advancement detection scheme and speculative contacts can get you down to microsecond tier fidelity pretty cheaply. (Incidentally, this specific problem is why I built that particular form of continuous collision detection :P) You're definitely right though that it's not going to magically solve away hardware level concerns.

On that front, one of the things I had to end up doing to ensure physical consistency was bite the bullet on a level of indirection. This can be flat out necessary on a gameplay level- allowing full 1:1 control often leads to pretty nasty pathologies and difficulty with correct physical responses. A truly physical character's motion can never truly match the input motion, since your controller is dramatically more nimble than even a light 2.5 pound longsword and the physical sword may be interfered with. This introduces some challenges on the side of user responsiveness and intuition, to be sure, but the physical motion also smooths out input and seems to make small scale controller imprecision a distant concern to the player. If the player can adapt to the physical indirection, they tend to allow a lot more leeway. This becomes even more valuable when trying to hide latency. If you have physically reasonable accelerations, networking overhead becomes a whole lot less objectionable.

There are definitely tradeoffs- the feeling of being a puppeteer takes some time to get used to.

I would expect you'd have to go DEEP into cognitive science to find a good model for this stuff. E.g.:



> There are plenty reasons that it might be true that no games that you know of shipped with a robust real-time solver for sword-sword collisions other than computational complexity.

This is the kind of comment that makes me just want to skip HN altogether. Why on earth are you arguing this at all — the counter to a point I never made — and why are you arguing from a position of ignorance like it makes you smarter than me?

You don’t have to pull an opinion out of your ass here. Just try it, the way my sibling poster has. This is a mathematically hard problem, and it will constrain your game design, and I think that’s really interesting.

You really don’t have to be a dick about it.

HN can definitely be annoying when commenters act like they know more than they do. No question about it. But please don't let it trigger you into lashing out, which only makes the thread worse. Instead, remember that the vast majority of readers are here to learn, and if you know more, sharing some of what you know, or some of your experience, is really helpful to them.


p.s. On another note, can you please stop creating accounts for every few comments you post? We ban accounts that do that. This is in the site guidelines too. HN is a community. Users needn't use their real name, but do need some identity for others to relate to. Otherwise we may as well have no usernames and no community, and that would be a different kind of forum. https://hn.algolia.com/?sort=byDate&dateRange=all&type=comme...

Is there a reason hn admins can't send direct messages to users, as opposed to calling them out publicly for things like this? I suppose doing it this way is probably more effective in changing behavior.

That's the main reason for doing it publicly, yes. We do try not to seem like we're picking on anybody personally.

I just don't see how your observation (that you are not aware of any game that solves the problem well) leads to your conclusion (that its solution is computationally complex). I can see that there may be other lines of reasoning that support that conclusion, for example something pertaining to the algorithms and techniques involved, but I also see how other conclusions may be true given your observation.

> Why on earth are you arguing this at all — the counter to a point I never made — and why are you arguing from a position of ignorance like it makes you smarter than me?

You are reading way too much into my post. I am arguing from a position of ignorance, but under no pretense that it somehow makes me smarter than you. On the contrary, it seems like you are familiar with the problem, and I think that you may have made much more relevant observations than the one you posted, but because my post has already prompted a more detailed description of the problem and its potential solutions I don't have to wait through petty insults to hear about it.

Good note!

In the real world bullet collisions are definitely not trivial. Video games do a laughable job at modeling the ballistics of projectiles. They don't even account for bullet drop.

When was the last time you saw a bullet do this in a video game? https://www.youtube.com/watch?v=0ABGIJwiGBc

If you do some light reading on "terminal ballistics", "experts" can't even agree on the lethality of bullet designs, especially in handguns.

People love to assume their models are accurate when they are usually educated guesses with gaping holes. Ballistics is no exception.

First time I actually saw the bullet drop was the original Quake more than 20 years ago.

Set the FOV to some narrow angle to give yourself a sniper sight, go to a long corridor, take a nail gun, shoot horizontally along the length of it. You will see how nails end up below the aiming cross.

If it were a rounding error, the nails would end up randomly distributed the aiming cross.

Alas, shotgun did not sport the same effect IIRC, though the hit of every individual pellet was accounted for separately.

There's actually many games that account for bullet drop! The article talks about this, but off the top of my head there's PUBG, and any game that involves a bow and arrow as a weapon.

Battlefield one of the most popular FPS has been doing bullet drop from a while.


https://youtu.be/cix07R1vlhI Arma 3 is the most advanced I know of, accounting for bullet drop and speed loss when passing through different objects with different caliburs

Project reality, squad even more advanced with wind and smth about earth rotation I forgot the Name of it

There's also the ace3 mod for Arma 3 which makes bullets behave more real

Video games in general do a poor job, but there are some exceptions. The Delta Force[1] for example did bullet drop 20 years ago, as well as Novalogic's multiplayer game Joint Operations: Typhoon Rising from 2004 which also supported up to 150 players per server.

[1]: https://en.wikipedia.org/wiki/Delta_Force_(video_game)

[2]: https://en.wikipedia.org/wiki/Joint_Operations:_Typhoon_Risi...

Some games do model bullet drop.

They didn't touch upon sound events.

Arma for instance you hear sound of the the bullet whizzing by or crashing into an object. After, you hear the sound of the bullet actually being fired (as bullets move faster then sound). This really threw me off at first, but really adds an immersive effect. The farther you are away, the longer the distance between the two sounds.

This is one of my favorite aspects of PUBG. A bullet flying really close to you will crack loudly. Just a bit farther and it’s a whizzing sound. Even farther and it’s only the boom of the explosion straight out of the gun that you hear. In the first two examples you can hear the bullet fly from left to right or whichever direction it came from to help pinpoint where it came from. And in all the examples you can hear pretty accurately where the gunshot originated. Even the timing differences between the explosion and the impact help with gauging distance. They did an incredible job on realism in that respect.

Disclaimer: not a game programmer so I could be completely wrong.

If you’ve implemented hitscan, the easiest implementation would be to find other players within some distance along the ray, and play some sound effect where the intensity of the whizzing sound is a function of the other players distance from the ray. The whizzing sound should provide some sense of direction of the bullet relative to the direction another player is facing. Possibly playing a pre recorded sound from a map of available sounds? Eg a bullet rushing from your 2 o’clock just past your shoulder? Or you could try to mix the sound and create that effect in real time I suppose.

That’s cool. Are there other games that do this?

I play a lot of pubg(player unknowns battlegrounds) and you can often hear the bullet whizzing past you before the initial shot of the gun/rifle/bullet. And you can often gauge how far away someone shot because of this.

Which is why more elaborately funded real-World armies are deploying suppressors on line-issue rifles.

Without the muzzle report the enemy has a much more difficult task in assessing distance and direction to the source of fire.

combat flight simulators like DCS and IL2 have this.

Back in college I had this course during which we were supposed to design an object-oriented app in Java using concurrency and networking - games were the usual use case.

Our professor asked us how would we implement hit detection - there were a few answers, but none touched the underlying idea that when there's no agent(user, AI) input, objects move in a predictable way, so the distance between them is some function of time.

For example the distance function of two objects moving in a linear fashion is (IIRC) a squared parabola, so you only need to sample three points in time to get the whole function.

And, of course, you only need to recalculate this function for objects that changed direction.

I've worked on a hobby ballistics simulator for some time now. This is of course a well studied field, with military applications going back hundreds of years. What's interesting (well, it was to me) is that the state if the art is not closed form solutions, because as you refine solutions and take into account bullet spin, wind, Coriolis effect etc, that becomes too cumbersome. Modern ballistics uses discrete simulation to calculate trajectories.

Something like montecarlo sequential resampling? Do you have any good papers you could reference?

Why would you use Monte Carlo for this? There's no randomness as stated. What op is probably talking about is numerical solutions to pdes (which is also considered "simulation").

"Ballistics: Theory and Design of Guns and Ammunition" by Carlucci et al. is (from what I can tell - again I'm just a hobbiest, it's the book I work from most) a thorough yet accessible standard work on this topic, detailed in the mathematics, lots of references, covers most of the details that matter, yet 'practical' - you can tell the authors were in the military where they had to produce results and not just papers. I'm not 100% sure how to exactly classify the approach in terms of mathematics. It's basically just 'over the next 10 cm, the bullet drops this much, yaws this much, rolls this much, ...' etc, so basically just incrementally calculating position. Very 'primitive' from a math point of view, but that's exactly what I found interesting - how a brute force numerical approach is considered superior to an elegant closed form solution.

Edit: I should add that part of the reason for this is that some of the external forces on a bullet are non-continuous, like wind coming around a building. That sort of pesky real world effects makes elegant solutions a lot more difficult.

This sounds a lot like what GP is saying, a time integration algorithm to solve a set of ODEs. Probably it's a variant of velocity Verlet?


When I started reading ‘college’ and ‘OOP’, for a moment I feared a solution that every bullet should be an object... :)

They are objects with a reference to the gun that fired it and everything it could possibly interact with in the game and indeed the game itself. How else is it going to have a “shoot()” method with no arguments?

Gamasutra fortunately is mostly written by actual professionals.

> […] for a moment I feared a solution that every bullet should be an object.

Why not, if you use the flyweight pattern?

Is that really a problem outside of large scale RTS games like Supreme Commander? I would be surprised if something like Counter Strike would see more than maybe a few dozen concurrently flying bullets in any possible situation.

I think each bullet in Supreme Commander IS it's own object. I know they nearly all are individually simulated. That game is STILL hard to run at high framerates in certain "5000 unit vs 5000 unit" circumstances

I think thijsvandien meant object not in terms of simulation, but in terms of architecture: An instance of a Bullet class, instead of some sort of fancy representation optimized for SIMD.

Just fyi. I thought counter strike didn't used projectiles but used raycasts for almost every weapon.

But your point still stands and applies for most shooters.

If you want to read further on this topic the term is “continuous collision detection”. Bullet physics is a good open source physics library with it implemented.

> For example the distance function of two objects moving in a linear fashion is (IIRC) a squared parabola

This is only true for points. It’s demonstrably untrue for arbitrary shapes.

Well, actually it's also true for spheres.

Then you can approximate any shape with spheres and use that as an optimisation before actually calculating the more costly distance functions.

Approximating a (solid) object with spheres means the spheres are in constant distance and angles with each other. So their trajectories are no longer linear if there is any kind of rotation.

The point isn't to approximate a solid object as several spheres, but to approximate it with one enclosing sphere. If two objects aren't close enough for their bounding spheres to touch, then you don't need to do a collision detection using the more complicated geometry.

Oh, right. Thanks for the clarification.

What is a linear rotation? If one sphere is in linear rotation, why can't two?

Are there any good resources for people interested in how multi-player networking/state management works?

I've written these articles, and they're usually well received: https://gabrielgambetta.com/client-server-game-architecture....

Your site says you taught computer graphics for a while. Do you have any other resources to recommend, or even a list of suggested topics? I really enjoyed my intro to computer graphics course but wasn’t able to take any follow ups

Sure! I've written a full book about that: https://gabrielgambetta.com/computer-graphics-from-scratch/i... Currently working with No Starch Press to turn it into a real book :)

Can confirm; these are great

Thank you :) Glad you find them useful.

Seconded, thanks for sharing

It can be a large topic dependent of the type of game, whether physics and such is involved etc... but I bookmarked this article from before which gave a good overview

part 1: https://medium.com/@qingweilim/how-do-multiplayer-games-sync...

part 2: https://medium.com/@qingweilim/how-do-multiplayer-game-sync-...

Might be worth looking at the HN thread about angeldu.st a couple of days ago; lots of discussion and links there about world state

This article about networking (as implemented in Source Engine, but applies to most realtime games) is a worthwhile read: https://developer.valvesoftware.com/wiki/Source_Multiplayer_...

I have played a bullet hell type game (2d) where bullets were actual 2d objects (mostly discs) but the player ship's hitbox was just a point, even though the ship itself was drawn as a somewhat bigger shape.

I guess this made the collision detection a bit faster and also made the game more dramatic - the close calls were bullets passing through the ship.

FFXIV has the same point mass hitbox as there's a large discrepancy for player model size.

This caused problems for one of our tanks about two expansions ago where his class' combat stance combined with being the largest race had his character model stand entirely outside the hitbox.

FFXIV, like (some?) other MMOs, also has no collisions between player characters. So you are frequently expected to “stack” your hit“boxes” at the same point.

It would be interesting to see if that was a game design decision to allow for the game to be more dramatic.

There's something called "Coyote Time" which is named after Wile E. Coyote and him staying in the air for a few seconds before gravity takes effect. Often in platformers, there's an invisible collision box added after cliffs so that if the user was slightly late pressing jump at the edge of the cliff, they would still make it as the invisible collision box would provide an extra step. It's an example of improving gameplay and game feel without being realistic.

Having your ship's hitbox be a single pixel is pretty standard in bullet-hell games. I'd say "drama" probably figured into that choice, it's really common to see enemies shoot out a little arc of bullets that slowly spread out as they travel, and watching a decent player fly their ship right through the gaps in that arc is cool.

> It would be interesting to see if that was a game design decision to allow for the game to be more dramatic.

It is, it's called "grazing."

Small hitboxes are just small hitboxes. "Grazing" specifically means closely approaching things that are harmful to touch, usually because the game rewards it in some way. This makes the game more fun by encouraging the player to take risks. It's been around for a long time, but AFAIK the first game to use it as a core mechanic was Psyvariar (2000), where it's used to power up your ship.

Seems like it should be older than this. Lotus Land Story (Touhou Project #4) has a graze counter, but being a doujin game it should be riffing off of other games that use graze for scoring or as a mechanic.

Ah interesting, not come across that term for game design, thanks!

It's a term used by players more so than designers I think - you usually get more points or something for getting as close as possible to bullets without getting hit, and some really dense patterns will require it, because the bullet sprites will practically be filling the screen.

It's possibly also worth mentioning for people unfamiliar with danmaku games that most are one hit kills against the player.

If it's called Coyote Time, then the box needs to disappear after the grace period, right? I mean if someone stops over the invisible box and never presses the button they should fall after all.

There's a few ways of implementing these input grace periods. For example just allowing jumps to trigger within a time period after last contact with the ground. No extra collision needed. It doesn't need to be taken too literally.

Of course, that's one of those things you can't tell the players. Like that game where the first killing blow (within some timeout) on the player automatically misses. It makes it more fun.

Nah, it's actually an explicit conceit in danmaku games (the style described by GP). In Touhou, when you press shift to move slowly, it shows your hitbox as that single point. There's no point in hiding it from the player, because there is no way to even survive if the hitbox weren't a single point. There are often only a few pixels of clearance in between the waves of bullets.

Consider this: https://www.youtube.com/watch?v=AY7QEEnSGVU

EDIT: Or this, https://www.youtube.com/watch?v=JJgy5skcMJI

At the end, you can really see the boss's frustration with the player as the beautifully ordered patterns devolve into an angry display of brute force as she throws every kind of bullet in the game at you at once.

I think it was explicit in the instructions.

Point to disc collision doesn't seem like it would be significantly simpler than disc to disc collision. In both cases the most expensive computation is calculating the square distance between the objects, which can be done with a table lookup and an addition. In point to disc collision you then determine if the squared distance is less than the squared radius of the disc, in which case you have a collision. The only difference in disc-to-disc collision is that you compare to the square sum of both radii instead.

Moreover, this kind of collision system is often used in games on systems where the hardware is capable of reporting pixel perfect sprite overlaps anyway, so I think you're on track when you say it's for dramatic effect. IME it's also frustrating in games where this isn't the case because you feel cheated when you die because a shot barely grazed some antenna.

I'm making an action MMO with both ballistic bullets and sword fighting:

1) If you look at how Nintendo solved ping-pong with Wiimote Plus (gyroscope addon) after the obvious letdown of the Wiimote standalone (only accelerometer): they gamified it, there is no 1:1 and the game is still fun. VR prooves this case too, as non-superhuman input is hard to sell after you give a man the mouse!

2) Ballistics are expensive on MMO's because you don't want a proper physics engine on the server. Two solutions I imagined: A) you chunk the projectiles temporal movement as vectors and add those to a 2D array that loops over time and has a limited amount of concurrent bullets per frame. B) You make a distributed voting system where other players detect and report hits to offload the server.

For sword fights I think left/right/jump/spin attack should be enough to get the player into the minigame of parrying and attacking interleaved (against many enemies). You just need to work on the abstraction so it's as fast in latency as possible and then make sure it's fun. The most important thing is to not try to simulate reality, reality is boring.

Look at how PoP Sands-of-time did it?

This is a decent primer, but when it comes to actually implementing projectiles in games, things get more complicated (games are very complex).

It’s important to keep performance considerations in mind, and be cognizant of when the performance characteristics change. For instance, if you’re working on a networked game, you have a huge set of constraints on what’s “easy” and what’s “performant” that do not exist in offline games. The projectile code is some of the most complicated in our engine just so that syncing state is consistent.

But right now I’m working on a boss fight, so I can optimize some damage code by only checking the projectile’s distance from the player against the projectile radius, instead of doing raycasts through our damage system. I also have more control of which things in the environment can be damaged by projectiles; another example of games being complex with lots of moving parts.

I like how tying physics to FPS is mentioned as an ill-advised thing to do.

Destiny 2 not that long ago had an issue with the Cold Heart laser where players on the PC port could output gamebreaking damage by jacking up their FPS as the laser would tick per frame (presumably) so the advice resonated

I feel like this is the first thing you learn as a game developer, and it's still mind blowing to me that big games still make this mistakes nowadays.

Even in Counter-Strike, back in the days, you'd be slightly more floaty when you cranked your FPS above 150, some went up to 1000 or more.

Why would that damage be calculated client side?

I have no clue as I was just a player - perhaps the client issued "shot fired" messages tied to frames per second

This doesn’t answer the question I was really hoping to see discusses. The target dot on screen defines a ray from the camera outward. The muzzle isn’t on that ray, nor is it even parallel to it, but the muzzle defines another ray. Which does the bullet follow?

Depends on the game: Counter-Strike, Quake and most casual games use the crosshair as bullet origin. More simulation focused games like Arma, PUBG, etc. use the actual barrel - some of them also show a bullet intersection marker when you'd hit something very close that your crosshair doesn't cover.

Good primer, one quibble: ballistics aren't really computationally complex, as the article suggests, but rather _hard to sync over a network_. Local dead-reckoning to compensate for latency, but still ensure all players see the same result (esp e.g. crits like headshots) is thorny.

That’s not true though. Bullet trajectories are perfectly predictable. Even something like wind can be known at the time of a bullet firing.

It’s no more complicated to sync that than to sync a straight line. ARMA does it.

EDIT: If it sounds like I’m saying “syncing bullets is effortless and there are no complications,” you’re reading too much into this. My objection is that bullets are fundamentally easier to sync than players, because they’re perfectly predictable, and you have to sync players already.

Bullet trajectories are predictable. Player movement is not (entirely - but you can usually make educated guesses). How do you determine that within the margin of network latency player A didn't move out of B's bullet trajectory?

It's an exercise in time travel. The server has to maintain previous states and estimate based on lag where each client thought each other client was when the shot was fired. Valve has a great article on it: https://developer.valvesoftware.com/wiki/Source_Multiplayer_...

This is the standard way of doing real-time networked multiplayer games, first pioneered by John Carmack in the Quakeworld codebase in 1996

> Instead of expecting everyone's messages to be dealt with at once, I now deal with each packet as it comes in. That player alone is moved forward in time, and a custom response is sent out in very short order. The rest of the objects in the world are spread out between the incoming packets. There are a lot of issues that that brings up. Time is no longer advancing uniformly for all objects in the world, which can cause a lot of problems.

> It works, though! The average time from a packet ariving at the system to the time a response is sent back is down to under 4ms, as opposed to over 50 with the old dedicated servers.

> Another side benefit is that the server never blindly sends packets out into the void, they must be specifically asked for (note that this is NOT a strict request/reply, because the client is streaming request without waiting for the replies).

> I am going to be adding bandwidth estimation to help out modem links. If quake knows that a link is clogged up, it can choose not to send anything else, which is far, far better than letting the network buffer everything up or randomly drop packets. A dialup line can just say "never send more than 2000 bytes a second in datagrams", and while the update rate may drop in an overcommited situation, the latency will never pile up like it can with the current version of quake.

> The biggest difference is the addition of client side movement simulation.

> I am now allowing the client to guess at the results of the users movement until the authoritative response from the server comes through. This is a biiiig architectural change. The client now needs to know about solidity of objects, friction, gravity, etc. I am sad to see the elegent client-as-terminal setup go away, but I am practical above idealistic.


Lag compensation is a (negligible?) violation of never trusting the client, as it gives the client the ability to inflate its own latency statistics until some critical moment. Not sure how reliably it can be exploited in practice, but if the stakes are high enough...

Basically every networked multiplayer shooter has to trust the client; even if it's as basic as "did the player put their cursor over this guy's head"

Never trusting the client just means the server must assume any messages from the client may have been manipulated or fabricated. A message like "the cursor is over this guy's head" would be an egregious mistake in the protocol because the client can easily lie about that. Lag compensation is more subtle because it's the timing between messages that may be manipulated, only for a small fraction of a second, and the client will have some uncertainty about the server's actual lag estimate. But it could be abused, for example, to trick the server into applying a "player shoots" command 50 ms earlier than it otherwise would.

This reminds me of Tribes Ascend snipers wanting to play with bigger latency because the adjustment would help them more than the lower ping.

OFP/ARMA family uses parabolas. You need just 2 measurements at 2 time points to calculate a hit. This is also perfectly suited for calculation with SSE in less than a kilocycle.

UE does bruteforce calculation as I know.

They also do deflections when you're firing at, e.g., a thin wooden wall a bullet can go through or something hard hit at a shallow angle causing a ricochet.

That has nothing to do with bullets. That’s saying “network syncing is complicated,” which is true.

Bullets are no more special in that regard than any network entity.

They’re fast moving relative to network latency and the error margins are small (off by a little is the difference between a kill and a miss).

And the impact is high, users will notice very quickly things are off

For example, Battlefield 3 and later does it by putting most of not all of the trust in the client. If I shoot at you, my client will calculate if that was a hit or not, and if so, send a message to the server saying how much damage I did to you.

This lead to a lot of "fun" instances of you seeing me, running behind cover, but due to lag those messages didn't reach me, so I kill you on my screen while you end up dying while in cover.

It's not about syncing the arc, it's about syncing a result that is now _asynchronous_ (what did the projectile hit? How is the world changed by that hit? Could the projectile be dodged after it was fired?). For game-meaningful results like headshots, crits, interrupts, or environmental-destructibles if the players can't "agree" concurrently, then the skill-ceiling is compromised, and you'll lose high-level players.

You’re talking about simulating the flight of the bullet over time. You don’t need to do that if all you want to simulate are the effects of gravity, wind, and distance on the bullet. You can pre-compute all of those things and simply add a delay based on the distance and muzzle velocity.

Sure, if you’re interested in simulating the effects of rifling and turbulence on the bullet, then you’re getting into fluid mechanics where the temperature and composition of the atmosphere make a difference. That seems like overkill for a game.

> EDIT: If it sounds like I’m saying “syncing bullets is effortless and there are no complications,” you’re reading too much into this.

Always make the assumption at least some people will take the most trivial interpretation of your comment on the internet. You have to balance between addressing them and not wasting time.

That’s well put. Someone recently asked about the integer value of NULL. I had a fever from infection, no one was answer the question and some were downvoting it to gray. “I’m going to regret this...” So I feverishly threw some defines from header files to point out how the answer could be self-serve. Like fucking zombies catching a scent, the pedants crawled out of the walls. Where were y’all eight hours ago?

> ballistics aren't really computationally complex

I’m not sure I would I agree with this.

Even hitscan projectiles for a game like Call of Duty or Battlefield is intense. Dozens of players running around with high rate of fire machine guns in complex geometric environments. It’s a significant cost.

Ballistic trajectories are pretty complex. Adding primitive bullet drop is definitely a huge increase in computational cost.

And that’s just for fake ballistic. Real bullet ballistics are “solved” empirically. There’s a bunch of formulas with a bunch of coefficients. And real bullets are fired at a real range to calculate the coefficients. It’s crazy complex.


Memory costs tend to dominate server side environments rather than CPU usage, though. How often is a player firing a gun? Every player in fortnite could fire at once and that’s still only 100 parabolas. Even if you devoted yourself to creating the most realistic bullet simulator, I would bet $10 that you’d be able to run that on any server that normally runs videogames. Pretty sure I’d go home with $20 in my pocket.

Tracing a parabola into short segments isn’t too horribly expensive. Intersecting that parabola with static and dynamic world geometry is less cheap.

Fortnite used to have pretty bad early game performance. Games are defined by their worst case. Early game could have a few dozen players firing high-rate of fire weapons. 100 server shots per second would be a regular occurrence.

Non-hitscan projectiles might also increase networking costs. Although for fast-moving invisible bullets you could probably don’t need to send them.

The actual server cost for shooters is generally resimulating the world for each player. Adding simulated bullets would make this even more expensive.

I think unless a profiler is telling you it’s expensive, then there is almost no chance you’ll guess it correctly on a modern CPU. I’ve done it a couple times, but I’ve been wrong far more often.

Why are a few hundred raycasts per frame expensive? In detail? I was doing a few hundred raycasts per frame back in 2008 at 60fps. So all this talk about expensive raycasts strikes me as “someone hasn’t tried it.”

Physics engines are so advanced that it’s mind boggling just how much work goes into their efficiency. There are legions of programmer-physicists who have spent their entire working careers just getting another 5% efficiency out of their algorithms. I could buy that 100k raycasts at 20fps might be expensive on modern machines, in specific circumstances. But 100? No chance.

Casting a ray into a world with millions of triangles is not terribly cheap. Tracing a parabola through that world is significantly more expensive. Tracing an arbitrary trajectory with simulated drop/drag is even worse.

Game servers often run at a mere 20Hz or 30Hz. Getting to 60 is hard. The question isn’t merely “is it expensive”. It’s “what’s the worst case and how expensive it is to add on top of what we already do”. Is 1 millisecond a lot or a little? (Spoiler: it’s a lot)

Modern CPUs are fast. But single threaded performance hasn’t improved exponentially. You could technically throw cores at the probably. But games want to maximize total server instances. You’re not likely going to throw 8 cores at one instance.

Go download Unity and find a reasonably complex scene. Start calling Physics.Raycast with different locations and directions. See how many calls you can make in 1ms.

Casting rays into a world with millions of triangles is in fact pretty darn cheap now. Again, I will wager you $10 that you can cast hundreds of rays per tick with zero perceptual loss in performance.

If you drop by 1ms for 100 raycasts, the physics engine is broken.

I mean this in the nicest way: have you tried it? If you do, you’ll discover you can cast almost as many rays as you want, against almost arbitrarily complex scenes. Whatever the server is using for its physics representation (which you need anyway) is what rays will use. And you’re already simulating some physics at 20Hz.

I used 60Hz to point out I was already casting hundreds of rays at 60Hz in 2008. Servers have only gotten better and faster, and the scenes have become exponentially more complex.

But if you won’t try it, you won’t try it. I can’t really think of any other way to make the point, short of pulling up a chart showing how many millions of raycasts you can do now against scenes with millions of triangles.

The whole point of spatial data structures is that you don’t have to check millions of triangles, even if your scene has millions of triangles.

I think unity has caused a lot of harm in the sense that devs have no idea what it’s actually doing. Ray.Cast might as well be black magic. Is it expensive? Who knows? Maybe it takes 16ms per raycast!

The worse part is that Ray.Cast also becomes the lens through which devs view the world. If unity’s raycast system is slow, then suddenly “all games everywhere cannot do this thing.” But unity is often slow!

Yeah man. I’ve got some experience dealing with raycasts. Not really interested in getting into a resume fight.

We’re a bit off the original point. Which is whether ballistics are computationally complex. I’d say so. Lots of players, lots of guns, complex geometry (static and dynamic). Pretty much everyone has had to deal with optimizing raycasts.

Parabolic arcs are even more expensive to intersect. And we’ve not even thrown AI into the mix. I’m not sure I’ve ever seen an AI drop a bullet through a narrow gap across a map. But TBH not many games have ballistics to begin with. Much less ballistics plus AI. I’m sure there’s a few. But it isn’t common.

What’s complicated about the entry-level kinematics equations that you can solve by hand with algebra and learn as a high school student?

Is it thorny given that there should be a library for all of this by now?

A library to magically solve the hardest fundamental problem of concurrency? Not so much.

That's a silly question considering game developers start with an entire game engine. So obviously, no, it's not "thorny" from the perspective of a modern game developer starting today.

That is basic abstraction which underlies all software...

Minor nitpick, the latest Call of Duty uses ballistics on all guns, not hitscan.

I'm working on the bullet system for a game right now and another advantage of hitscan I think, that wasn't explicitly mentioned in the article, is that you can get objects behind objects to then determine if the first object should absorb some of the bullet damage. For example, an enemy behind a wall may still damage but not as much as if the shots were fired directly at the player.

When you send out the raycast and get a list of all objects hit, you can iterate over the objects hit and reduce damage value until the first enemy object is hit (pending any distance restrictions).

You can do that when simulating each bullets trajectory as well. For example straightforward setup for collision detection would be a raycast per bullet per tick and as such can work much the same way.

Indeed you can, but the idea is that a raycast is still needed. I should've been more specific in that it doesn't mean the projectile system can't do it but the idea of raycasting allows for that additional advantage cheaply and easily.

Yeah the key differentiator is a trade off between cost and simulation fidelity.

It is mentioned in the article, with the example of Quake's railgun.

Speaking as someone who has no knowledge of game programming why is raycasting implemented as a light speed traveling thing? Could they have not done the travel computations on a local buffer and add the effects of gravity or other components and then composite he resultant and rendered to screen? Why does it have to be real time? Too memory hungry for that?

Rays are just a geometric primitive defined by a starting point and a direction. So a single raycast based weapon can conceptually fire infinitely far in a single test, so much faster than the speed of light. Collision tests are just the result of calculating the point of intersection between it and other primitives.

Games run in discreet time steps called frames or ticks. Bullets travel can then be simulated in several ways for example using numerical integration to apply forces to each bullet for the time step to calculate its new position, collision testing the line segment (“raycasting”) between the position of the last frame and the new position and calculating and displaying the results.

Imagine it is 1992. You have an 80286 and a 256-color framebuffer. You need to fill that buffer with a new frame at least every 100ms to have any hope of having something like "an action game" instead of "a vaguely interactive slideshow".

You have spent the past month or three writing and optimizing some very slick code that draws a first-person view of a maze, with textured walls and floors. Everyone's jaws drop when you show it to them. It takes about 75-90ms to draw a frame on that 80286.

You have next to no time left to run game logic in. Simulating a handful of active enemies and processing player inputs pretty much eat up the rest of the time. But you have this raycasting routine that you optimized the hell out of because it's in the middle of one of the hottest parts of the display-rendering code. So you reuse that as your "is the player aimed at an enemy when they clicked" check. It's good enough, especially since the game's largely set in a tight labyrinth with few spaces large enough that a more realistically simulated bullet wouldn't get to your target in the time between one frame and the next anyway.

When you upgrade your view renderer to handle non-grid-aligned walls and arbitrary heights for your next game, you don't bother simulating better bullets. It's still Good Enough - you're targeting a faster CPU now but you're still doing all the rendering yourself because GPUs don't even exist yet, and your rendering is more complicated now and you still only have about 5% of the CPU time left for game logic.

You start licensing your view renderer to other game companies. ("You", in this story, are pretty much John Romero.) Other people start writing similar game engines but they make similar decisions for similar reasons; "realistic bullet physics" would be nice to have but that's a lot less impressive than "this game can actually render objects with a triple-digit number of polygons while maintaining a decent framerate and resolution".

This situation persists for quite some time until "3D accelerator cards" become something you can expect the average computer owner to have, and you can start spending CPU time on "simulating a more complex world".

(It is also worth noting that 2D games written in this timeframe would generally show bullets as visible objects with an exaggeratedly slow travel time, so the player had a chance to dodge them. Rendering 2D stuff is a lot cheaper.)

For Wolf3D, the player was the only one using full hitscan. Enemies simply decided hit or not based on a dice throw, adjusted with distance to player. Worked well enough until you start noticing they shoot trough almost-closed doors, eaxh other, etc...

Doom did a lot better, hence the monster infighting

100ms a frame is a vaguely interactive slide show.

Generally speaking it feels better and makes for better gameplay, even if that gameplay is unrealistic. Most games have projectile weapons that have some lead time so there isn't much of a performance reason.

HN users tend to think deeper/more complex simulation is directly correlated to better gameplay (see the sword conversation above), but one of the interesting things about games is abstraction.

That said more simulation focused games with larger maps (some Battlefield games, ARMA) have bullets with travel velocities and bullet drop.

I think you're confusing raycasting with hitscan. They're very similar. Hitscan does that light-speed-line thing you're describing and instantly delivers a "bullet" along it.

Raycasting instead takes the light-speed-line information and runs some process like "What could we do to make this play out convincingly?" Then based on that information, it adds the gravity effects and other stuff to what plays out.

You might raycast right before a jump to determine what landing animation your player will ultimately use. That's important during the jump because it makes it look more convincing.

Raycasts are cheap because they are just two points with an implied line between. Projectiles are great because they are a basic shape inserted into your preexisting physics sim that handles realistic looking gravity and collisions with everything else that has a collision shape. You could have projectiles ricochet off each other.

Precomputing a trajectory loses the dynamics of collision and the cheapness of rays.

Fixing projected actions into the future from one point in time can make for weird lag effects and unpredictable results for the player when a moveable piece interrupts a fixed bullet path.

It depends on what do you want to use. You can do bullet with raycast or You can simply adding velocity to the bullet or you can move the bullet as projectile in vector 3 and calculate the trajectory of the bullet. You can generate random point inside circle to add error in your final position of the bullet

Flyweights with a recycled object pool I would think.

Very informative. Thank you!

I wonder if mainstream games will at some point evolve out of the shooting-and-killing focus.

FIFA, Mario Kart, Pokémon? Mainstream is a lot more than just shooters...

(I don't really feel like Pokemon is the best counterexample? The bulk of the game mechanics are still about applying violence to an opponent, it's just mediated by cutesy animals instead of guns and the game stops short of calling the victory condition "killing" because it's for kids.)

> the game stops short of calling the victory condition "killing" because it's for kids.

There is death in the series, end-of-battle fainting is explicitly a different thing (probably better thought of as "knocked unconscious").

The first generation even had the tower in Lavender Town, filled with the graves of dead pokemon.

In any case, GP's comment stands: Pokemon is neither a shooter nor focused on killing.

Only about half are shooting/killing games. But pretend-killing games are a major part of our mammalian brains, going back millions of years, as seen in your local house cat.


Games allow people to try out things that are not possible for most people in real life.

It includes doing a medieval quest, becoming an action mercenary, becoming a ninja, managing a top football team, building a city, building a theme park, participating in World Wars, building a space program, rescuing hostages etc.

The focus on violence means that such violence is percieved as beyond the reach of most in real life, which is good news.

That's a bit like saying "I wonder if movies will evolve out of the defeating the villain focus". Sure there's plenty of that but the medium is so massive you can find something to suit any taste. I like shooters and they were still only about a third of the games I played this year.

Movie action scenes are typically equal ingredients vs other scenes, but in games they are typically the dominant way of exercising player agency, big difference.

Besides shooters, combat dominates adventure and open world games, which could be done differently too.

> Movie action scenes are typically equal ingredients vs other scenes, but in games they are typically the dominant way of exercising player agency, big difference.

> Besides shooters, combat dominates adventure and open world games, which could be done differently too.

Could you elaborate on this a bit? To contrast, I think of Fallout 3. Sure, there is a lot of violence out in the wasteland and it kind of stinks that I can't, say, reason with mutants. But at the same time, I would not characterize the dominant expression of agency being mediated through violence, but dialog. Are there any games specifically (besides those with a shooting focus like Battlefield, Call of Duty, etc) that capture your sentiments?

In the way books and films have evolved out of shooting and killing?

I enjoy a lot of videogames that are all about shooting and killing. I also enjoy a bunch that aren't. Yet it makes me sad that in so many games, across genres, the application of violence is the primary lever with which the player can apply their intent to the game world, and a lot of game design revolves around increasingly elaborate systems determining just how deadly that violence is.

I'm not gonna stop enjoying my murder sprees through hordes of monsters powered by a google-maps-worthy talent tree and several spreadsheets worth of magic sword optimization out of some moral objection to violence, but I'd be very happy to see the same degree of sophistication and mechanical depth applied to other game mechanics as well, and probably feel better about that hobby of mine as a whole then.

It's hard to engagingly gamify conversations, working on your slide deck / spreadsheets, elevator pitches etc. as routes to apply agency into the world.

Tense situations are generally dangerous, and games tend to thrive on tension. Beyond abstract puzzles, simulations tend towards activities which are actually dangerous and discouraged in the real world; if it's not violence, it might be theft (Thief / Dishonored), high wire acrobatics (Mirror's Edge), high speed driving, etc.

Yeah, I don't really disagree. Though, I do feel like a lot of videogame violence is so detached from trying to simulate real-life combat (because it's building on decades worth of genre conventions more than anything) that it's abstract enough that you might as well use it to model just about any other kind of conflict or interaction in a game.

You can always play simulation games like Kerbal Space program or Cities Skylines. Those still have a tech tree although it may not be as complicated as the skill trees in Path of Exile or the class tree in Trees of Savior.

Because escapism involves leaving the norms, and most people are fortunate enough that violence is outside their normal life experience.

They never had that focus in the same degree. Count the percentage of time that's violent action in novels/films vs mainstream games, it's nowhere close. Or count the percent of nonviolent titles in yearly critically acclaimed works.

Novels and films are comparatively passive media. It's hard to gamify a stream of consciousness, the dance of a camera around a scene, or a conversation in quite the same way; conversation trees get tedious, cutscenes drag on too long and the game risks turning into an interactive movie, or end up with a walking simulator etc.

There's a place for those things but there's a different balance of pacing and tension. Most games more closely resemble thrillers because there's more intense experiences packed in.

Casual games are the ones that use hitscan? Name a single competitive shooter that uses any bullet system other than hitscan.

I think you misinterpreted what was written.

> "A lot of “casual” games end up using the hitscan method as it simplifies the learning curve for most beginner players. But what about games that aim to create an “immersive and realistic” shooting experience? They cannot achieve their goals within these constraints. We need to use an alternative method."

It's not saying casual games are the only games to use hitscan but it's usually easier and quicker to implement hitscans than projectiles (and more intuitive for casual gamers).

Half Life and Halo both use the hybrid system depending on the weapon, as written in the article.

I'm not sure what you mean by "competitive", but there are many non-casual games that don't use hitscan. Off the top of my head, Arma and Red Orchestra.

I would argue that both counter strike and Call of Duty are casual arcade games, despite them being played competitively. Battlefield and Arma instead are not (as) arcadey games and thus do not use hitscan.

CS is not an arcade shooter because there is significant mechanical complexity (i.e. skill) to using weapons.

Guns in Battlefield are far easier to use in comparison.

tl;dr hitscan or not does not correlate with ease of use.

Having complex mechanics on one part of the game does not make the game a non-arcade. It is arcadey on the sense of how it is played. You're playing in small enclosed areas and it is extremely easy to pick up the game. Of course, you can learn the spray patterns but it is not at all required to play the game.

The battlefield series in turn, while not really realistic, has way more moving parts in it thus making it less arcadey.

I don't think map size has any factor in "arcadeness". The degree to which mechanical complexity exists and interacts with different aspects of the game is. CS traditionally has a huge skill gap where other games don't have any, e.g. in Battlefield movement is relatively irrelevant; so to get kills, you can largely just rely on aim. In CS, only having aim will not get you many kills at all (the most obvious issue being that you will simply miss most shots, irrespective of how well your aiming ability put the crosshair on the opponent).

> The battlefield series in turn, while not really realistic, has way more moving parts in it thus making it less arcadey.

I think you vastly underestimate just how complex CS is and how many gameplay elements are intermingled to make plays happen at higher levels of play. As a long time player of both BF and CS... BF has more "stuff" and more things going on at the same time (mostly due to large number of players and vehicles), but is definitely not the more complex game.

On top of that, CS even at medium levels of play, is more about game sense (strategy, understanding your enemies positioning and reactions to stimuli, timing, ... game sense in itself is a vast sea of complexity) and communication than raw mechanical skill, although the latter can to some extent compensate for the lack of the former. At high levels of play, purely mechanically skilled players are... worthless.

Is this even true? The only thing "skillful" about CS guns is that they have fixed spray patterns. Otherwise it's very much point and shoot because they're all hitscan. Burst fire weapons (which aren't very popular in CS afaik) take slightly more skill, but still, projectile weapons are objectively more difficult.

As a high level cs player I would argue that the ingame movement and how it interacts with the gunplay is more important to master than the spray patterns.

> The only thing "skillful" about CS guns is that they have fixed spray patterns. Otherwise it's very much point and shoot because they're all hitscan.

It's free to play, download it and see for yourself how "point and shoot" weapons in CS are.

Slightly less snarky - in CS shooting while moving (as practiced in most other shooters, including BF and CoD) is extremely inaccurate, sometimes comically so (close up, you will miss your opponent, despite your gun barrel visually sticking into their player model). This means that just to fire a gun accurately you require good left/right hand coordination (you move with the left hand, and aim and shoot with the right). For example, you might strafe left to check a corner, register an enemy, you will then flick on their had and synchronize your counterstrafing with your shot. This might sound simple, but the skill ceiling is extremely high.

As a long time player of both BF, CoD and CS (all versions) I can tell you that the gunplay of CS is by far the most difficult to master (or rather, get to a half decent level) out of all popular shooters.

The time to kill in CS is very low - often zero.

> Burst fire weapons (which aren't very popular in CS afaik) take slightly more skill, but still, projectile weapons are objectively more difficult.

In most games burst fire weapons are easier to use than their full-auto counterparts, since their bursts are often artificially more accurate than manual bursts

To be clear, I played well over 1000 hours in 1.6, I'm not new to the game! I've also played CS:GO, but only 50 hours or so.

I think you might be getting things backwards. The fact that it has a low time to kill means it takes less skill to get a kill. When a fight takes longer, there are more opportunities for the higher skill player to increase their advantage over a lower skill player. This is a pretty well-known relationship in game design.

To put it another way, if you look at a game with a long time to kill, like a fighting game or moba, if you put a top 1% player vs a top 5% player in a 1v1, the better player will ALWAYS win every single encounter (assuming equal start). This is because even if the better makes a mistake, or the worse player gets lucky, the fight is long enough to compensate for that.

In a game like CS, because the time to kill is so fast, it only takes one single mistake by the better player and the worse player will win the encounter.

I should clarify that like most games, I think CS still has a very high skill ceiling, but a ton of it is in communication/positioning/knowledge and also the kind of "raw skill" like reaction time that can't fully be trained.

I don't think comparing TTK across genres makes much sense, since e.g. in a fighting game a single kill is an entire round of the game.

> When a fight takes longer, there are more opportunities for the higher skill player to increase their advantage over a lower skill player. [Therefore making the game more skillful]

I very much disagree. Letting your opponent get the drop on you is a major mistake. The game giving you opportunities to plaster over huge blunders easily does not make it more skillful.

In CS you have short time to kill, long time to reset, precisely to make positioning and game sense more important and to heavily punish whiffing. If a slightly better player in terms of mechanical skill could always just do a 180° and get the kill regardless of how poor their positioning was, you are clearly not increasing the skill gap of the game. Rather you end up with a CoD-style experience.

Similarly, the importance of a single kill in CS varies widely. It could be relatively inconsequential, or it could decide the round (even if it is the first kill in a 5v5).

> In a game like CS, because the time to kill is so fast, it only takes one single mistake by the better player and the worse player will win the encounter.

That's the point of the game's design. You can't and shouldn't expect raw mechanical skill to save you every single time if you get yourself into a bad situation. Sometimes it might, some bad situations are also very hard to avoid. But if you keep getting into bad situations w.r.t. to your opponent you are clearly not the better CS player. Similar to racing, if you get off the track in a corner, your mistake was seven corners before that.

Sorry for the late response, I forgot to check this thread for a while...

This original thread started with a discussion about the mechanical complexity ("skill") of CS. Not positioning, game sense, etc. Though other games have that stuff too!

> The game giving you opportunities to plaster over huge blunders easily does not make it more skillful.

The thing is, having a long time to kill doesn't really allow you to plaster over anything, at least not at a high enough level. Once you're at the highest tier of a game, every single one of those positioning + game sense decisions matters too... but then raw mechanics wise, those long ttk games are more complex than CS.

Spray patterns as well as different timings for accuracy reset between shots. The skill ceiling is very high...

Being played competitively doesn't make them competitive? Am I understanding this correctly?

Explanation for the downvotes would be nice. The parent comment to mine really doesn't make sense to me.

(I didn't down vote your post, but I just want to state my opinion)

Just because people play a game competitively, it doesn't make the game inherently competitive. For example, many people play Minecraft competitively; that doesn't make Minecraft a competitive game, just a game that you can play competitively.

Does Minecraft have million dollar tournaments?

I think they meant "casual" as opposite of "immersive and realistic" (same sentence in the article), not as "non competitive".

I think they meant "casual" in a conventional sense as "easy to get into" as they talk about "simplifying learning curve". So opposite of it is "hard to get into", and "immersive and realistic" is one kind of such games, but not the only one.

PUBG is not hitscan. Fornite snipers are not hitscan. I’m sure there are plenty of other examples, but there’s two competitive ones. I would agree though that most FPSs are hitscan, at least for “fast” (e.g. bullets rather than rockets) projectiles.

Many of the weapons in Overwatch and all but one weapon in Apex Legends are non-hitscan.

Correct. This is perhaps most clearly an intentional design decision with Ana from Overwatch who has a gun that switches from projectile to hitscan depending on whether you are scoped in.

Many competitive shooters use ballistics calculations, Battlefield, Apex Legends to name a few.

BF doesn't even have a comp mode built in... are there even any PUG providers for it?

I'm not sure the exact definition of "competitive shooter", but I thought Fortnite used a mix, and this old Reddit thread seemed to confirm that.


Yes, casual games also use hitscan. Given the sentence follows a paragraph mentioning several other shooters that also at least partially use hitscan, it's fairly clear that they do not claim that only casual games use it.

The article also provides examples answering your second demand.

Things like rockets tend to not be hitscan.

Quake 3 (now Quakelive or Quake Champions): rocket launcher, granade launcher, plasma gun, nail gun.

Ok: Overwatch, Battlefield, PUBG, Escape From Tarkov.

the new call of duty is not hitscan IIRC?

Great post! Informative and interesting

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact