Search Unity

Collider or ray cast for melee weapons

Discussion in 'General Discussion' started by JovanD, Jun 18, 2014.

  1. JovanD

    JovanD

    Joined:
    Jan 5, 2014
    Posts:
    205
    So what do you guys think? Which is more efficient/accurate?
     
  2. randomperson42

    randomperson42

    Joined:
    Jun 29, 2013
    Posts:
    974
    It depends entirely on what you want to do with your game. Physics-based combat may require more skill on the part of the player, and might be more difficult to implement. As far as efficiency is concerned, it depends once again on what you want for your specific game. Different styles of games use different combat systems. Either method could potentially be more/less efficient and accurate than the other, it just depends on how far you take it. Your question is very vague.

    In the end it just depends on what you want for your game.
     
    frosted likes this.
  3. Meltdown

    Meltdown

    Joined:
    Oct 13, 2010
    Posts:
    5,822
    Depends on the weapon. If it's a sniper rifle with instant hit, a ray cast might be best. If its a grenade launcher or shotgun, colliders will be better.
     
  4. randomperson42

    randomperson42

    Joined:
    Jun 29, 2013
    Posts:
    974
    Yeah but in the title he says "for melee weapons."
     
  5. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    Go with colliders and triggers for melee combat. Chances are that the motion is slow enough that colliders will register all hits, unlike with bullets and the like that may travel right through and past a gameObject during the course of a frame.
     
  6. Meltdown

    Meltdown

    Joined:
    Oct 13, 2010
    Posts:
    5,822
    Oops, missed that one.

    For melee a ray cast doesn't make any sense. Definately a set of colliders on the weapon, (to determine which part of the weapon hit the opponent), and a few colliders on the various body parts.
     
  7. Not_Sure

    Not_Sure

    Joined:
    Dec 13, 2011
    Posts:
    3,546
    Telescoping can be remedied by using rays drawn between the two points from of a moving object in between frames.

    I believe the physics engine does this by default, and it's what stops objects from falling through terrain constantly.

    The trouble is that a lot of "bullets" are teleported in each frame rather than moving.

    Here's a great article about it:
    http://www.militantgame.com/web/cla...day-3d-game-how-projectiles-work-in-militant/



    That said, back to the OP, I too would like to know what works best for different kinds of melee.
     
    Last edited: Jun 18, 2014
  8. Meltdown

    Meltdown

    Joined:
    Oct 13, 2010
    Posts:
    5,822
  9. Not_Sure

    Not_Sure

    Joined:
    Dec 13, 2011
    Posts:
    3,546
    Huh, you're right. I just checked it and sure enough with enough speed objects do fall right through the terrain. That's odd, I figured that would be like physics engine 101.

    Thanks for the link, btw.
     
  10. randomperson42

    randomperson42

    Joined:
    Jun 29, 2013
    Posts:
    974
    Yeah that's one way to do it. But a lot of RPG games and such have targetting systems and automatic combat which is not physics based. If you're going for that kind of game, raycasting is better. I kind of agree though, physics based combat is more fun. :)

    Melee motion might be slow enough, but not necessarily. Often the swing of a sword will be too fast as well. However, there is something you can do about this in Unity if you use rigidbodies. In the rigidbody component you can change the collision detection mode. This will tell Unity to detect collisions for fast moving objects. Very useful, especially for projectiles.
    http://docs.unity3d.com/Manual/class-Rigidbody.html
     
  11. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    Well, solving it can be pretty "101", but it's a compromise you might intentionally make for performance. Unity's physics system does indeed let you pick, thats what the "continuous" collision detection is meant for (though I'm not sure how effective it is).



    As for what to do with melee weapons, triggers and colliders are the typical way to go, but they're not the only way to go. I would not start with the assumption that movement will be slow enough to hit things reliably within frame deltas unless that kind of slow movement is a deliberate part of your design. There are plenty of games (e.g.: Ninja Gaiden springs to mind) where animations are so fast that the character is nearly snapping from pose to pose - how fast do you think the tip of those swords are moving?

    I also wouldn't assume that you necessarily even want to apply hits based on contacts alone. That makes physical sense, but does it make game design sense? Plenty of games use the concept of a "hit frame", which is some kind of time marker in an attack animation which tells the game at which time of the attack to apply damage.

    Last time I implemented melee attacks I did a "hit frame" accompanied by a trigger. Anything in the trigger during the hit frame had damage applied. The trigger didn't move because it didn't have to, all it did was keep a list of what's currently touching it for the damage part of the script to use when applying damage in the hit frame.

    Another approach you could use is a hit frame and either a bunch of test points in the weapon or a physics sweep test between the previous and current positions of the weapon, or along a spline which defines the sweep. Or, you could do sweep tests each frame and keep a list of things you've already applied damage to in the current attack to avoid repeating it... unless you want to repeat it, which you might. (If accuracy was important, I'd probably use splines or something for the sweep test, since point-to-point tests would get less accurate at longer ranges.) Or, you could use continuous collision detection and just use the various collision callbacks.

    Plenty of ways to skin this cat. Knowing which one to use really depends on how you want your combat to actually work.
    - How fast will it be?
    - How do you want to apply damage?
    - What approach will you take to balancing your game?
    - What kinds of weapons will you have?
    - What type of animation do you want to have?
    - How do you want the player to control it?
    - Do you want it to be deterministic?
    - So on and so forth...
     
    Last edited: Jun 19, 2014
  12. Meltdown

    Meltdown

    Joined:
    Oct 13, 2010
    Posts:
    5,822


    People who make games with auto-targeting/button mashing weapon systems should be dragged out into the street and shot! Hence I would never advocate such a system for melee. Agreed, physics based targeting and 'real combat' are much more satisfying and interesting.
     
  13. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    Depends on the game and the accuracy requirements.

    I would think a distance check would be the best option generally... think wow...

    but if you want the melee to make physical contact, then colliders... they work better with animated weapons.
     
  14. Tiny-Tree

    Tiny-Tree

    Joined:
    Dec 26, 2012
    Posts:
    1,315
    You could use sphere cast, cast it only during the animation momentum and in the direction the weapon move
     
  15. Not_Sure

    Not_Sure

    Joined:
    Dec 13, 2011
    Posts:
    3,546
    That makes a lot of sense.
    Thank you!


    Back to the OP:
    So to clarify, a game like Diablo 3 when you attack one target you would most likely use a ray and distance followed with an animation. Then when you do a sweeping move you would use "splines" to cast a ray through the objects being hit.

    Then a game like Elder Scrolls would use a collider on the weapon and a collider on the target, then have a frame count as the "hit" frame and either have the target do an animation or have their collider move with physics from the point of collision.

    And of course, colliders for things like spells and area effects.

    Is that about right?
     
    Last edited: Jun 19, 2014
  16. Kinos141

    Kinos141

    Joined:
    Jun 22, 2011
    Posts:
    969
    It depends on the game. If you are talking about FPS knife swipe like it CoD, I'd use a cone or sphere trigger, so that the knife doesn't have to be accurate, but it'll still hit the enemy.
    If it's a third person game like Devil May Cry, then I'd use a triggers. The tricky part is getting the trigger to activate(take health) ONLY on swings, and not when player is just walking around with it. For that, you will have to know the animation system!
     
  17. RockoDyne

    RockoDyne

    Joined:
    Apr 10, 2014
    Posts:
    2,234
    It will all be dependent. If it's weighted and not ludicrously fast, then basic colliders should be fine, otherwise you may need to play around with hitboxes to give physics more slack. If you make the colliders while taking into account that physics won't catch everything, then it shouldn't be a problem.

    So long as you are aware of what can be used and in what situations they should be used, then more power to you.
     
  18. BrandyStarbrite

    BrandyStarbrite

    Joined:
    Aug 4, 2013
    Posts:
    2,076
    Wooah! This is interesting read.
    So, in a game such as the Soul Calibur on the Dreamcast.
    The Dreamcast version, not the sequels.
    How do you guy's, think the Soul Calibur dev. team back in 1998 would have approached this weapons melee combat thing?
     
  19. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    For games like diablo/wow I expect they only use distance, and a ray if it involves a line of sight element.

    There's nothing gained by using a ray except for players missing the target (and getting frustrated)
     
  20. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    It could also be useful for occlusion checks - so that if you're attacking a group of enemies only those in the front row get damaged.

    But in general, yes, this kind of simple approach (check distance -> angle -> occlusion) can work wonders.

    While I use more complicated systems now (as you can probably tell), in my early days of writing games I used to use spheres for collision detection, for everything. Spaceship? Sphere. Zombie? Sphere. UFO? Sphere. Sometimes I'd text that sphere against a box, if I was getting advanced. ;) I'd roll my own collision detection systems inn an hour or less, and use that for the entire length of a game project.

    Why? Because I'd decide early on to fix it when players told me it was a problem... and they never told me it was a problem! As long as you make it feel good players typically won't get upset about the fine-grained details of things they can't actually see. Draw a big trail on your sword swipes or whatever you've got, and make sure that enemies look like they're responding appropriately. Between those two things you won't usually actually need accurate collision detection - players aren't watching your game in slow-motion to see if the damage triggers when and where the sword actually connects to each enemy.
     
    Ryiah and dreasgrech like this.
  21. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    One thing I have noticed when gaming vs developing..

    When im developing, I spend a lot of time staring intently at the animations/collisions etc to ensure they look accurate and realisitc, but when im gaming, I dont pay any attention to those details (beyond the really obvious stuff like fps aim).

    Do I notice things like distance being odd, or graphics/animations looking wrong? no. Im focused entirely on the game play task. Sure it has to look nice, but its easy to get caught up too much in how accurate something is.

    Classic example, im working on a smartphone runner/platform style game that involves a lot of animation, and when im developing it on my large screens, I notice every little flaw in the animation and spend way too much time trying to get it perfect. Atm the runner is automatic, so I can stare intently at the animations...

    When im actually playing the game on a smartphone, do you know what im looking at? Guess what, its not the animation. Its the screen queues that are telling me the moves I need to do. My sole focus is somewhere completely different.

    This is all kind of going off on a bit of a tangent from the main subject of this thread, but its something to consider all the same.
     
  22. RockoDyne

    RockoDyne

    Joined:
    Apr 10, 2014
    Posts:
    2,234
    This is kind of a transparent aspect. So long as it is works and isn't betraying your expectations for collision, then it's perfect and doesn't need to be improved.
     
    BennyKokMusic and angrypenguin like this.
  23. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    And bam! Spot on. ;)

    That, along with what JamesLeeNZ said, is precisely why I think more about what's useful at design time than about what leads to precisely correct details. What's more, getting those details "correct" is often to the detriment of other aspects of a game. For example, what's better in, say, a Prince of Persia style game - a trap that's modelled physically correctly, or a trap that's very clear about precisely when it is and is not going to kill you?

    Giving me more power to tweak things to feel right as a designer improves the quality of my games far more than getting pixel-perfect whatever, so when I choose where to spend my time...
     
  24. derf

    derf

    Joined:
    Aug 14, 2011
    Posts:
    356
    Not many melee games use colliders/triggers even third person games (there are some though) as it creates more work on the engine to validate all objects and the degree of contact between colliders and triggers of the objects. Granted only objects that HAVE triggers are considered.

    A good number of them still use Distance and Line of Sight (LOS) between OBJECT_A and OBJECT_B and time the animations to when it calculates a potential hit. Most models have similar timed animations even if they are performing different methods of attack (normal attack, combo attack, super attack, etc.).

    It does sound counter-intuitive, but it actually gives you the most control over the game performance.
    Some games don't even care about animations to physical strike (MMORPG's come to mind) and it is always distance and line of sight or just plain distance.

    A game that uses colliders with melee weapons would be Jedi Knight Academy 2 and the lightsaber. To test this just pop out the lightsaber blade and let it collide with a wall, a computer terminal, etc. and it plays the sounds and draws the damage on the surface of the object, basically it reacts to the collider on the lightsaber. Even if you turn your blade into Kyle Katarn on the missions he helps you or Chewbacca on the mission he helps you on it reacts to colliding with them, but Knights of the Old Republic (the single player one, not the MMORPG one) the lightsaber can be passing right through an NPC, a wall, a door and they do not react to it.
     
    betaFlux likes this.
  25. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    A lightsaber burning a wall doesn't need a collider. That could also just be a raycast.
     
  26. RockoDyne

    RockoDyne

    Joined:
    Apr 10, 2014
    Posts:
    2,234
    Unless you wanted to cut through multiple objects/pay attention to multiple object interactions.
     
  27. Marble

    Marble

    Joined:
    Aug 29, 2005
    Posts:
    1,268
    Raycasts don't need to terminate at their first intersection, though.

    I'm using the collider (actually trigger) method because I want melee weapons to be able to collide with each other. If I didn't have this requirement, I would probably use one of the simpler methods discussed.
     
  28. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    That's right. That kind of thing is a bit of a pain point in Unity (thanks to GC), but more broadly speaking it's a non-issue.
     
  29. Not_Sure

    Not_Sure

    Joined:
    Dec 13, 2011
    Posts:
    3,546
    Wow, thanks everyone!

    This is a wealth of things to think about and consider.
     
  30. derf

    derf

    Joined:
    Aug 14, 2011
    Posts:
    356
    Lightsabers collide with each other and make the crashing sound when they hit, so no raycast. Like I said, most melee games do not use physics and colliders; it uses more complexity to accomplish it and depending on the game play style it may be overkill; so they use simple distance and line of site and fake the rest, there are exceptions just like Jedi Knight games.
     
  31. RockoDyne

    RockoDyne

    Joined:
    Apr 10, 2014
    Posts:
    2,234
    My second thought is, wouldn't you also need to set up multiple raycasts? For cutting a wall, you would want one going down the blade, but for swinging at ludicrous speed, you would want to cast back from the way it moved.

    You would have to use both as neither one alone solves the other's problem reliably.
     
  32. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    For what it's worth, I was speaking specifically to one use case within the implementation of a lightsaber, to which a raycast is a perfectly adequate solution.

    That aside, though, why does that mean "no raycast"? Who ever said that a single approach must solve all use cases at once?

    Just like RokoDyne is getting at, different use cases call for different solutions, and there's well documented math available for a wide variety of them. For instance, why not use raycasts for the passive scorching effect, polygon-polygon checks against other lightsabers (since both are fast moving, thin objects that could easily move through each other in a frame, and this is a very simple way to get reliable continuous detection), and polygon-primitive/mesh checks against slow moving or static objects?

    (Note that while this sounds crazy in today's world of grab-a-physics-library-off-the-shelf, back in the days of Jedi Knight it was common to roll your own. And since the physics library can still do most of the work for us we only have to look after parts of the special cases.)

    Also, it's worth noting that while the handle of a lightsaber is a normal physics object, the beam part is not - it's a dense bar of light - and, as such, doesn't behave according to normal physics rules. For instance, when the beam collides with things it doesn't bounce off as a solid object would, it gets truncated and starts burning a hole in whatever it's colliding with. Even putting aside the burning of the hole, this means that trivial use of standard physics libraries wouldn't get the whole job done.

    And lastly, check out my first post in this thread. ;)
     
    Last edited: Jun 22, 2014
    Eluem and chelnok like this.
  33. SunnyChow

    SunnyChow

    Joined:
    Jun 6, 2013
    Posts:
    360
    What kind of game is it? Is it 1on1 fight game? or ARPG? first person view?
     
  34. Shbli

    Shbli

    Joined:
    Jan 28, 2014
    Posts:
    126
    That's a bit old thread I was researching an answer for, but got to develop my own simpler solution.

    I though I would share it, maybe useful to someone, or I can get a feedback on it.

    I wouldn't use any, the moment the sword is in a position to decrease the health of the monster, I would add an event in the animation system, then add a code at that event to first check the distance between the "Sword" and the "Monster" or "Enemy", the distance need to be super small (Maybe 0.5 or so)

    I'm implementing this right now, let's see how it goes, no colliers, no raycast.
     
  35. Eluem

    Eluem

    Joined:
    Apr 13, 2013
    Posts:
    57
    I didn't read the entire thread, but you might want to look into how Chivalry: Medieval Warfare handles their melee collision detection.

    I'm currently making a top down 2d melee combat game with a lot of swords and such. I'm using the built-in animation system to animate my weapon's swings.

    Initially I was using box colliders to handle the collisions but they would jump over the players sometimes (pretty rarely) even with slow weapons. I believe this is likely because, since I'm animating the attacks and not using the physics engine to directly move them, it can't properly autocast them for me.

    I moved from using that to using a series of raycasts going down the blade for horizontal slashes (I change the formation for thrusts and overheads, since it's 2D).

    It works way better now. However, even with a solution like this, if a player's framerate somehow drops (due to having other processes running in the background, for example) then the range of the weapon will become shorter since the arc will be less smooth.

    Hope this help anyone that's working on a melee combat focused game.
     
  36. Eluem

    Eluem

    Joined:
    Apr 13, 2013
    Posts:
    57
    This is an interesting idea... however, with a system like this you can only have it work somewhat reliably if you're trying to implement melee combat with attacks that last very few frames. Basically, if I understand what you're describing correctly, you're effectively "firing" a psuedo collision check in front of the actor at a specific frame of the animation.

    That'll definitely work and, depending on the mechanics of the game and the level of accuracy required, you might not need collision checks at all. Just a simple distance and angle check against every enemy could be done. However, then you need to have access to all of that information in that event.. which isn't something that really works the "Unity Way" :p

    I'm curious as to how it went, seeing as your post is over a year old.

    Good luck :D
     
  37. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,566
    angrypenguin likes this.
  38. Eluem

    Eluem

    Joined:
    Apr 13, 2013
    Posts:
    57
    That was the first thing I tried, didn't seem to work. I did a lot of testing with it and tried messing around with the frame rates, setting them really low to give me hints about the behavior.

    You have to set it to animate with physics and then I think it'll work, but it was still choppy... And that made the animations look really off.

    I already implemented the chivalry method months ago, and it's working amazingly well so far.
     
    angrypenguin likes this.
  39. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    That sounds like the hitbox method, but:
    - You're using a sphere instead of a box (a distance check is the same as a sphere collision check), and
    - Your sphere is moving, because it is attached to the weapon.

    There's still the distinct possibility that the weapon could move through the enemy without triggering a hit, especially if you have to resort to small distance values to get good hit resolution, because it's possible to move from one side of the collision zone to the other if you get a long frame in your animation. You're also sacrificing a lot of precision and/or control by essentially simplifying it to a sphere-sphere check.

    For what it's worth, colliders and raycasts aren't bad and shouldn't be avoided. If you need them, use them, that's what they're there for. As long as you're not wasteful with them you shouldn't have problems. Especially conisder that in the cases we're talking about here the colliders and/or raycasts need only be active for a very small portion of the time, and most characters won't be performing them most of the time. It's simply not an area where you have to scrimp. If a character needs to cast half a dozen rays each frame for half a second while swinging a sword, go for it, it's fine.

    (Aside: On a mobile game I made I had multiple guards shining torches around. The torch beam was created by casting a bunch of rays, recording their hit positions, and stitching a mesh along them so they didn't penetrate walls. That ran at 30+ fps on an iPhone 3GS, with 4+ guards casting... I don't know, but quite a few rays each. If you need some rays on your sword, just do it.)

    (Aside 2: I've also implemented games with nothing but sphere-sphere collision before because it's super quick to implement, generally pretty fast, and sometimes all you need. If it does get the job done then there's no need to make things any more complicated than that.)
     
  40. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,566
    I implemented similar system myself in the past, it is just that unity doesn't seem too optimized for making many raycasts, which is why I suggested trying collisionDetectionMode first (that would require attaching kinematic rigid body to the weapon).
     
  41. Eluem

    Eluem

    Joined:
    Apr 13, 2013
    Posts:
    57
    Hmm ah yes, I did try putting rigidbodies on my weapons as well, but I didn't really like how that worked out. So I wanted to avoid that.

    What was your experience with Unity having too many raycasts? Also, how many would you consider too many?

    I currently have about 17 raycasts that I do per frame while my largest weapon is swinging. I do have some plans for going over it and optimizing it a bit, removing some excess casts and possibly collapsing a few concepts to cut out 4 or 5, if needed.

    The game is designed to support a maximum of 10-16 players. They're also very short raycasts.

    Hmm maybe I'll go ahead and see what happens if I try to have 16 player characters swing their swords at once, see if it drops the FPS at all.
     
  42. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,566
    I had a stress test with few dozen melee combatants with melee weapons. Basically, I hit a big bottleneck with pathfinding and collision avoidance long before I hit any issue with raycast, mostly because raycast is not active all the time. However, that demo wasn't exactly profiled for performance and I have general impression that unity physics is less robust than, say, physics in unreal engine (unity not having "multiraycast" might have something to do with it).

    I think that using raycasts makes sense if you're creating something like soul calibur, and in generic hack and slash game it might be sufficient to just run sphere/box overlap on animation event.

    I also had no issue using them for "shotgun collider", but that was on PC platform (doing that on mobile would probably be a very bad idea).
     
  43. Eluem

    Eluem

    Joined:
    Apr 13, 2013
    Posts:
    57
    Hmm I'm not sure what a "multiraycast" is.. and a cursory googling for the term didn't bring up anything enlightening. Could you explain what you mean by that?

    I'm actually making a game pretty heavily inspired by dark souls. You can check it out on youtube if you want by looking up Helheim TurmoniousGames.

    We really want smooth paths for our attacks as they're relatively slow and they can be manipulated mid-swing by turning your character.

    If we were doing a different type of combat with faster more "snap" attacks.. where they can just animate really fast and fire out a hitbox for one frame or a few frames we could just pop a simple collision box up or use an "overlap" function... but I think the raycast is better for what we're doing. I'm currently overriding my controller code to allow me to force the player to attack so I can tell all of 16 players to attack at once and see if the game feels laggy lol
     
  44. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,566
    I meant that instead of querying one raycast of a time, you specify multiple rays at once, and make physics engine query them all at once. Less overhead this way, especially if physics runs on gpu.

    I worked with something very similar, it can be done with unity, as long as you don't try to spawn too many enemies at once. I gotta warn you that dealing with unity's animation controllers will be royal pain, but aside from that it can be done.

    test.jpg test2.jpg test3.jpg test4.jpg test5.jpg
    I do advise to investigate collision detection mode, because raycasts don't work for sword/sword collision when both swords are rapidly moving. Also... mecanim will be royal pain to deal with if your weapons are animated (because mecanim doesn't have weapon bones for props). There are also quirks, like OnTrigger/CollisionEnter/Leave being unreliablve and spherecasts failing to register if collision overlaps starting sphere....

    Anyway, you'll discover that as you continue working with unity.