Coding Math: Episode 14 - Collision Detection

Поділитися
Вставка
  • Опубліковано 16 січ 2025

КОМЕНТАРІ • 127

  • @giorgosd3624
    @giorgosd3624 6 років тому +27

    Btw the inRange() function can be done without using min() or max() and still be robust as follows:
    function inRange(x, a, b) {
    return x*x - (a+b)*x + a*b

  • @ohaRega
    @ohaRega 7 років тому +3

    Your channel is genius. I needed it so much.
    Subscribed. You are amazing. From the bottom of my heart, as an engineering student:
    thank you VERY much!

  • @nazerbs
    @nazerbs 10 років тому +70

    If you could show, circles and rectangles colliding that would be awesome!

    • @kevnar
      @kevnar 4 роки тому +1

      Run a for loop for every point along every side of the rectangle, and do rectangle-point collision on each of those points.

    • @erwindaguinotas4653
      @erwindaguinotas4653 4 роки тому

      Get the distance of every corner of the rectangle to the center and if atleast one if those points have a distance less that the radius, the the rectangle collided with the circle

    • @heckmarkus
      @heckmarkus 3 роки тому +4

      @@erwindaguinotas4653 if you only check the 4 corners you will miss collissions of the circle on the lines between the corners.

    • @Brahvim
      @Brahvim 3 роки тому

      @@kevnar Expensive (o_0)

    • @biglexica7339
      @biglexica7339 2 роки тому

      @@kevnar this isn't possible

  • @Raycast74
    @Raycast74 2 роки тому +1

    Even though I'm working from processing, your videos are very helpful and the circle circle collision is very easy to implement. Thanks for this very useful content.

  • @kevinbee4617
    @kevinbee4617 10 років тому +15

    There is a possible optimization for circle-on-circle collisions.
    You are doing this:
    utils.distance(c0, c1)

    • @kevinbee4617
      @kevinbee4617 10 років тому +3

      No criticism! Just a remark for the interested viewer.

    • @codingmath
      @codingmath  10 років тому +7

      Yes, this is a common optimization for this kind of thing. I didn't mention it here, but it's good to be aware of it, for sure.

    • @codingmath
      @codingmath  10 років тому +15

      kevin Bee No problem with criticism. As long as you're not trying to tear me down, I can take it. ;)

    • @benjaminhoving
      @benjaminhoving 8 років тому

      Simply using the length squared instead of lengths will also work. Just use a distance function that returns: x^2 + y^2 instead of sqrt(x^2 + y^2).

  • @peeterutsi4028
    @peeterutsi4028 9 років тому +31

    How about randomly rotated rectangle vs circle?

    • @liam6550
      @liam6550 5 років тому +3

      dunno how the guy in the vid would do it, but I would get the corner points of the rectangle, draw lines between them, and check for any intercept of the lines

    • @Hasnain1F
      @Hasnain1F 5 років тому +1

      That becomes complex. What you CAN do is to take each corner of both rects and compare it to the X and Y of your world. If values overlap each other, they are colliding. That's the only thing that comes to my beginner mind.

    • @kundanborakb
      @kundanborakb 5 років тому +5

      In tutorial all examples are based on AABB collision if you want randomly rotated rectangle you should read about SAT(separate axis theorem) .

    • @gws5314
      @gws5314 4 роки тому +1

      employ an army of employee in an office like tech support to check individually

  • @YOP888
    @YOP888 8 років тому +2

    Awesome! Your channel will be my school now.

  • @kevnar
    @kevnar 8 років тому +2

    So, you discussed how to detect a collision between circles, which I added to the particles class. Can you give some pointers on how to adjust the motion of two objects that have collided? The simplistic way is to just swap the velocity vectors of the two particles. I added that into the simulation, and checked all the collisions against each other in a nested for loop, and now the balls are bouncing off each other like some sort of insane billiard table.
    But it's a flawed reaction system. It assumes the collision was dead on, from the center of mass to the other center of mass. It doesn't factor in glancing strikes. A glancing strike would change the angles slightly.
    It also doesn't factor in the ratios of the masses of the two objects. A tiny ball striking a larger ball wouldn't send the larger ball flying in the other direction.
    If you can help me out with these factors, that would be awesome.

    • @gumbilicious1
      @gumbilicious1 7 років тому

      kevnar the physics equations would be elastic and inelastic collision equations. Wikipedia is a good starting place.
      The basics are that you need to make new resultant vectors once the collision is detected.

  • @gangstasteve5753
    @gangstasteve5753 4 роки тому +1

    damn im glad i found this channel

  • @mothtolias
    @mothtolias 8 років тому +1

    hey, I just want to say that I really love this series💙 it's really good and informative, and I feel like I'm learning a lot with them.

  • @MrSpektorDude
    @MrSpektorDude 9 років тому

    Thank you so much, you have opened the eyes for me on a subject that I was strugling with somuch, especialy on those rectangle and rectangle collision. I am now my own formula to try and make cube on cobe collision for my three js project. Thank you so much

    • @MrSpektorDude
      @MrSpektorDude 9 років тому

      I am sorry for the horible englisch i am in a hurry to get this working :D

    • @1DJLNR
      @1DJLNR 8 років тому

      collision detection is never accurate but more how you want it to be, i always thought the idea was simple, make transparent borders on each object around all object that should never collide..

  • @eminemoriginal1655
    @eminemoriginal1655 8 років тому +7

    He is pointing to deez nuts in 1:17

  • @frankbruder3097
    @frankbruder3097 4 роки тому

    Two rectangles _rect1, rect2_ overlap iff the top left corner of rect1 (rect1.x, rect1.y) is within the rectangle formed by extending rect2 to the left and up by the width and height of rect1, that is (rect2.x - rect1.width, rect2.y - rect1.height, rect1.width + rect2.width, rect1.height + rect2.height)
    Similarly, a circle rectangle collision detection can be transformed to a collision detection between a point and a rounded rectangle, and a rounded rectangle is a union of rectangles and circles.
    The circle _circle_ collides with the rectangle _rect_ iff the centre point of circle collides with any one of
    - Rectangle(rect.x - circle.r, rect.y, rect.width + 2*circle.r, rect.height)
    - Rectangle(rect.x, rect.y - circle.r, rect.width, rect.height + 2*circle.r)
    - Circle(rect.x, rect.y, circle.r)
    - Circle(rect.x + rect.width, rect.y, circle.r)
    - Circle(rect.x, rect.y + rect.height, circle.r)
    - Circle(rect.x + rect.width, rect.y + rect.height, circle.r)

  • @monicaramirez243
    @monicaramirez243 8 років тому +1

    Excellent video!

  • @TheNo1WarLord
    @TheNo1WarLord 10 років тому +6

    Sorry if this comment isn't relevant, but what IDE are you writing your code in?

    • @MuresanVladMihail
      @MuresanVladMihail 10 років тому +4

      Sublime Text Editor

    • @codingmath
      @codingmath  10 років тому +3

      Yup, Sublime.

    • @FernandoBasso
      @FernandoBasso 8 років тому +1

      And sublime is not an IDE, by the way.

    • @KeithPeters
      @KeithPeters 8 років тому +1

      "IDE" is a fuzzy term. I'd say it is. With all the various packages you can install for it, there's very little it can't do.

    • @oliveredholm4284
      @oliveredholm4284 8 років тому

      Sublime Text

  • @VinnieSajan
    @VinnieSajan 7 років тому +4

    my brain is growing

  • @charliemalmqvist1152
    @charliemalmqvist1152 7 років тому +3

    How would I check for collision if the rectangle is rotated?

  • @Technomancr
    @Technomancr 9 років тому +1

    For the circle example, you don't need to use Math.sqrt(); You can compare the distance^2 and the relationships stay the same, saving you processor cycles.

    • @KeithPeters
      @KeithPeters 9 років тому +1

      Check the previous comments. Everyone always likes to point this out like it's not something I've known for 15 years. ;)

  • @drrobotnik5376
    @drrobotnik5376 4 роки тому +1

    love the AABB intersection - you do it backwards and the code is simpler! =)

  • @sho1175
    @sho1175 4 роки тому

    5:23 sqrt is expensive, woudn't it be better to check for:
    dx * dx + dy * dy

    • @KeithPeters
      @KeithPeters 4 роки тому

      Asked and answered, probably multiple times.

    • @sho1175
      @sho1175 4 роки тому

      @@KeithPeters you're right, in 110 comments, another asks this ^^ I just didn't read them all before posting, and it didn't appear to the top, but I understand your frustration

    • @KeithPeters
      @KeithPeters 4 роки тому

      @@sho1175 Not just in this video, but in multiple other videos as well. It's a valid comment. I get it. Writing highly optimized code is not the same as teaching concepts. First you have to understand what you are doing and why. Then you can learn how to make it faster, leaner, etc. I just get tired of explaining that.

  • @emmanuels.r9957
    @emmanuels.r9957 9 років тому +3

    You can make a video of how to resolve collisions, I tried but I find it difficult to locate an a good algorithm

  • @flashjaysan1
    @flashjaysan1 7 років тому

    When I had to think about two rectangles colliding, I'd gone with the point and rectangle collision solution but extended for each corner of a rectangle. If any corner is inside the other rectangle, then it's colliding. I suppose it is less effective than your solution but it was the one I found.

    • @KeithPeters
      @KeithPeters 6 років тому

      jérôme Barbier picture a tall rectangle overlapping a wide one, so as to firm a + symbol. None of the corners are within the opposite rectangle.

    • @flashjaysan1
      @flashjaysan1 6 років тому

      Fantastic! Never thought about this possibility. Thanks for pointing that caveat to me!

  • @tekaaable
    @tekaaable 9 років тому

    Love your videos. Im going to take a class i Objectoriented programming i january and using your videos and python/pygame to prepare myself.

  • @zealous_carrot8744
    @zealous_carrot8744 2 роки тому

    hey,have ya made any video on rect-rect- collision resolution?

  • @INNoMATHsforyou
    @INNoMATHsforyou 8 років тому

    Sir you are doing a great job.. thank you.

  • @jimk907
    @jimk907 8 років тому +1

    Very nice series thank-you. Shouldn't the pointCircle function comparison be '

  • @TheLoLeKGaming
    @TheLoLeKGaming 7 років тому

    Great channel!

  • @NeuonAu
    @NeuonAu 9 років тому

    Amazing quality!

  • @ClearNinjaFox
    @ClearNinjaFox 9 років тому

    hey Keith im new to your channel i come from processing sent by Daniel Shiffman, im looking to learn about Trig for coding math, now im a little lost with the syntax as im new to java and now here im being introduce to Js damm...... well im looking to code my humanoid and im guessing i have to learn the coding math such as trig linear algebra for inverse kinematics and even jacobian matrix matrices and all that cray math that just come down to working out math using variables , now is there a reason why i never see algorithm for preventing obj from going thru each other ? i see your approach is to have the obj change colors if the collide but in the real world this is not going to be the case if you collide the only thing you might end up seeing is stars not colors lol SO how can one go about this type of implementation ? if im working out IK and my arm collides with its torso colors lol is not something i want to see in fact i want the arm to stop b4 the collision

  • @Jadakra
    @Jadakra 6 років тому

    What if you intersect a rectangle by another side? Do you have to check for intersections on each corner?

  • @anuraghazra4772
    @anuraghazra4772 7 років тому +3

    Hi Folks.. if you can make a episode for SAT(Separating Axis Theorem) then it would be very nice..Thanks in advance

  • @zachdyer1208
    @zachdyer1208 9 років тому +1

    How would i do collision detection in a roguelike. I have several rooms.

  • @astatat8972
    @astatat8972 2 роки тому

    What if I have lots of shapes? Do I need to make a nested loop to check if they intersect with each other? If so, it will be very inefficient.

  • @Packerman37
    @Packerman37 8 років тому

    Just found this channel yesterday and I can't get enough! Unfortunately, this video keeps stopping due to an error in the playback! I've tried on my laptop and now here on mobile. Is the problem on my end?

    • @KeithPeters
      @KeithPeters 8 років тому

      +Packerman37 It's either your network or a UA-cam glitch. The video is fine. :)

    • @1DJLNR
      @1DJLNR 8 років тому +1

      clear your app cache or watch from within a browser on device

  • @vladislavgusak2309
    @vladislavgusak2309 7 років тому

    It's so cool . It's very simply , but i did't thing of this , thanks .

  • @jim0_o
    @jim0_o 10 років тому

    What about objects like the SpaceShip you wrote that with Line and MoveTo wouldn't calculating overlap of stroke on that be pheasablly simple?
    If I'm not mistaken SVG files (vector graphics for browsers) read like lines or fill between vectors on a canvas (in xml format) so they could be used the same way? (unless JS or HTML5 deals with rendering SVG files on a much lower level)
    I know I'm commenting a lot and I might be all wrong, I just needed to get the idea down on "paper" so I could move on to your next video.

    • @KeithPeters
      @KeithPeters 10 років тому +1

      Yup the line intersection series that's in progress deals with just that kind of scenario. Should be another episode coming out soon.

  • @fwdflashwebdesign
    @fwdflashwebdesign 4 роки тому

    Great videos...

  • @danban2281
    @danban2281 4 роки тому

    Works perfect!!!

  • @NDTECH
    @NDTECH 7 років тому

    👍👍👍👍 nice tutorial

  • @Fire_Rice
    @Fire_Rice 4 роки тому

    what if one of the rectangles were rotated though?

    • @BlueProgamer212
      @BlueProgamer212 4 роки тому

      SAT (Seperating axis theorem) i can't explain this one.

    • @Fire_Rice
      @Fire_Rice 4 роки тому

      thanks.

  • @TheDorkol5
    @TheDorkol5 4 роки тому

    im just trying to get one rectangle to hit another and not go through it, i have already did the screen boundries but i can figure out how to get it to not pass through. can anyone point me int the right direction

  • @inferious777
    @inferious777 4 роки тому

    my question is *how* would one implement this? In a multi entity environment N, e.g 10, 20, 50, or even much more, if we were to check for every possible collision it would take O(N^2), as the amount of possible combinations of two entity collisions is N • N - 1 ~= N^2. This would take an absurdly long amount of time just for collision detection.

    • @KeithPeters
      @KeithPeters 4 роки тому +1

      One way I've seen is to divide the scene into a grid and assign each object to each grid cell that it overlaps. Then for each object, you only have to check the objects in the surrounding 8 cells. It's complex to set up, but can wind up saving a lot of checks. The overhead is only worth it if you have a certain number of objects to check.

    • @KeithPeters
      @KeithPeters 4 роки тому +1

      aka quad tree ua-cam.com/video/OJxEcs0w_kE/v-deo.html

    • @inferious777
      @inferious777 4 роки тому

      @@KeithPeters Thanks alot! I'll have to look into this.

  • @janakmedicos9735
    @janakmedicos9735 4 роки тому +1

    Detection and prevention.

  • @LuRybz
    @LuRybz 8 років тому

    What about collision resolution?

  • @elionddh
    @elionddh 7 років тому

    how is the name of this programming language that he is using ???

  • @Artur.Baranov
    @Artur.Baranov 10 років тому +1

    what if box was rotated? the X range and Y range wouldn't be so useful

    • @Jacob_Mango
      @Jacob_Mango 9 років тому +1

      ArchiZT you rotate the coordinates around aswell and reorder them in such a way that the calculations will work. Which I don't think you need to reorder them. Just rotate the coords.

  • @Zilarrezko
    @Zilarrezko 10 років тому

    hmm... in the Love2D community we use
    function boxCollision(x1, y1, w1, h1, x2, y2, w2, h2)
    return y1 < y2 + h2 and y2 < y1 + h1 and x1 < x2 + w2 and x2 < x1 + w1
    end
    In lua at least, might save a couple of processes not sure. I was wondering how we could make objects that don't allow collision, aka no overlapping, trying to wrap my head around that.

    • @KeithPeters
      @KeithPeters 10 років тому

      Yeah, essentially, that breaks down to the same thing I'm doing, except that I'm allowing for negative widths and heights. Try to make your function allow for that and will get a lot more complex.

  • @xkhokokox
    @xkhokokox 9 років тому

    what ide is that?

    • @ClearNinjaFox
      @ClearNinjaFox 9 років тому

      +domien van steendam refer to the very first video ever and you will get your answer

    • @OkenTheReal
      @OkenTheReal 8 років тому

      Sublime Text, check it out! It's awesome!

  • @YG-ub4dk
    @YG-ub4dk 6 років тому

    It's incomplete, what if one of the objects is moving at a speed great enough to pass from one side of the other object to its other side in just 1 frame? They never overlap so their collision will not be detected.

  • @spothogarfuneslora5908
    @spothogarfuneslora5908 10 років тому

    god bless you man

  • @worldofstrings
    @worldofstrings 9 років тому

    your teachings is Fantastic!!! Is your codes copy righted? Can I use your code for a specific project? I maybe want earn revenue with?

    • @KeithPeters
      @KeithPeters 9 років тому +2

      +randy franklin Please use it. That's what it's for! If you want to mention where you learned it that would be great.

  • @Nathsnirlgrdgg
    @Nathsnirlgrdgg 8 років тому

    Two rectangles are intersecting iff one corner is in another rectangle. This means you can use the same code for points intersecting rectangles, using the four corners of one rectangle as the points.

    • @lorencehernandez9250
      @lorencehernandez9250 8 років тому

      checking point if inside rectangle 4 times is inefficient

    • @Arganoid
      @Arganoid 8 років тому +3

      That won't detect all collisions. What if you have a tall, thin rectangle and a wide rectangle with a small height, and they overlap like a plus sign?

  • @xamogxusx
    @xamogxusx 5 років тому

    golden

  • @programmerpt970
    @programmerpt970 7 років тому

    Man thanks that helps me create a button

  • @androcoder1389
    @androcoder1389 4 роки тому

    what language he use ?? it's not a JavaScript 😕😕

    • @KeithPeters
      @KeithPeters 4 роки тому +1

      100% plain old vanilla javascript

    • @androcoder1389
      @androcoder1389 4 роки тому

      @@KeithPeters thx bro... 😁

  • @billybbob18
    @billybbob18 6 років тому +1

    Darn. I was hoping this was an example of preemptive detection. I'm trying to know if I'm going to hit something, not when I already did. Lol

    • @Ramblingroundys
      @Ramblingroundys 6 років тому

      You generally define the hit box, for you either create a second hit box representing the proximity test. The test is the same, as is the math. If you treat proximity as collision then what you have is still collision test but using larger hit box..

  • @szaman6204
    @szaman6204 2 роки тому

    kanał marzenie

  • @osere6432
    @osere6432 5 років тому +1

    Math.max fury road

  • @kylestankovich2199
    @kylestankovich2199 8 років тому

    Hello. I'm a Sophomore taking Geometry, which means I am by no means "advanced" in Math. I learn like everyone else else, your average Joe lol. So, can anyone recommend a book that would help my math skills for video games without being overly complex?

    • @KeithPeters
      @KeithPeters 8 років тому

      I agree. Trigonometry is at the core of almost any kind of graphical programming you'd want to do. There are a bunch of trig related videos here, and yeah, Khan Academy is a great resource as well.

  • @JamalNasirTV
    @JamalNasirTV 8 років тому +1

    Can someone tell me how you use this in C language?

    • @RazorM97
      @RazorM97 7 років тому

      it's like translating from two different languages, you need to understand how they work

    • @FFA704
      @FFA704 7 років тому +2

      This is basic 3rd grade maths, you shouldnt even need an example to implement this

    • @gingy2828
      @gingy2828 6 років тому

      I study C++ and a fuck ton of math at university and I still needed example code.

    • @samb443
      @samb443 6 років тому

      i dont study c++ but i was still able to write sample code in it, and im a fucking idiot

  • @katrix422
    @katrix422 8 років тому +3

    too fast

    • @katrix422
      @katrix422 8 років тому

      Hey kevin... m sorry.. i saw video again nd again
      . finally got it... sorry once again

    • @kelvinsmith4894
      @kelvinsmith4894 8 років тому +2

      Stop being ANNOYING ... simply slow it down from the player settings or PAUSE it and think,,,

  • @raven1552
    @raven1552 5 років тому

    Zajebiste.

  • @pumpkinot9900
    @pumpkinot9900 6 років тому

    What is the point of this video? Rectangles colliding with rectangles is the only hard thing.

  • @debbahisaad109
    @debbahisaad109 4 роки тому

    Coding trivial collision detection like you do at the pixel level is very very limited in practical use,cpu intensive... what would you do when having to manage hundreds or thousands of objects? Plus you should've provide a broad overview on collision detection first.... use quadtrees or Octrees in 3d, that's how it is done in real world, rarely pixelwise.

  • @nianyiwang6659
    @nianyiwang6659 7 років тому +1

    That Math.min() is killing me. Just use recursion!

  • @mothtolias
    @mothtolias 8 років тому +2

    hey, I just want to say that I really love this series💙 it's really good and informative, and I feel like I'm learning a lot with them.