Jump to content
  • Advertisement
Bob Dylan

Calculating direction after circle-circle collision

Recommended Posts

I know how to calculate the scalar of the velocity vector after a collision with 2 circles (as per this link: https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6331)

These circles cannot rotate and do not have friction but can have different masses, however I cannot seem to find out any way to find the unit vector that I need to multiply the scalar of velocity by to get the new velocity of the particles after the collision.

I also know how to check if 2 circles are colliding.

Also, I am only dealing with this in a purely "maths-sense" (ie. the circles have a center and a radius), and would like to know how I can represent these circles on the screen in python 3.0.

The vector class:

class Vector():
def __init__(self,x,y):
    self.x = x
    self.y = y

def add(self, newVector):
    return Vector(self.x+newVector.x, self.y+newVector.y)

def subtract(self,newVector):
    return Vector(self.x-newVector.x, self.y-newVector.y)

def equals(self, newVector):
    return Vector(newVector.x,newVector.y)

def scalarMult(self, scalar):
    return Vector(self.x*scalar, self.y*scalar)

def dotProduct(self, newVector):
    return (self.x*newVector.x)+(self.y*newVector.y

def distance(self):
    return math.sqrt((self.x)**2 +(self.y)**2)

The circle class:

class Particles():
def __init__(self,currentPos, oldPos, accel, dt,mass, center, radius):
    self.currentPos = currentPos
    self.oldPos = oldPos
    self.accel = accel
    self.dt = dt
    self.mass = mass
    self.center = center
    self.radius = radius

def doVerletPosition(currentPos, oldPos, accel, dt):
    a = currentPos.subtract(oldPos)
    b = currentPos.add(a)
    c = accel.scalarMult(dt)
    d = c.scalarMult(dt)
    return d.add(b)

def doVerletVelocity(currentPos, oldPos, dt):
    deltaD = (currentPos.subtract(oldPos))
    return deltaD.scalarMult(1/dt)

def collisionDetection(self, center, radius):
    xCenter = (self.radius).xComponent()
    yCenter = (self.radius).yComponent()
    xOther = radius.xComponent()
    yOther = radius.yComponent()
    if ((xCenter - xOther)**2 + (yCenter-yOther)**2 < (self.radius + radius)**2):
        return True
    else:
        return False

I do know about AABBs, but I am only using around 10 particles for now, and AABBs are not necessary now.

Share this post


Link to post
Share on other sites
Advertisement

The usual billiard physics will hopefully help you. It can be narrow down to weighted disks easily. I haven't read that link thought. But at first glance it covers what you are looking for.

Edited by _Silence_

Share this post


Link to post
Share on other sites

Ah that is somehow easy Its not that hard:

- You take the difference between the two centers in world space: R = B - A

- Normalize that and you have your direction: N = R / |R|

- Calculate the penetration distance by subtracting the summed radius of both circles from the projected difference by the direction (btw: This distance is the length of the difference): d = (RadiusA+RadiusB) - Dot(R, N)

- Calculate relative velocity: VAB = VA - VB

- Calculate impulse strength: j = -(1 + e) * Dot(VAB, N) / (1/MassA + 1/MassB);

- Calculate and apply impulse on velocities:

VA -= j * (1 / MassA) * N

VB += j * (1 / MassB) * N

 

Thats one step. Next step is to resolve penetration. This is handled in the "how to create a custom 2D physics engine" series as well - so check that out.

Edited by Finalspace

Share this post


Link to post
Share on other sites
34 minutes ago, Dirk Gregorius said:

This obviously has not the dimensions of an impulse.

Right, its not an impulse at all! My bad. Its a minimum translation vector!

An impulse would be at the relative velocity projected along the direction divided by the sum of their masses.

Edited by Finalspace

Share this post


Link to post
Share on other sites
Quote

An impulse would be at the relative velocity projected along the direction divided by the sum of their masses.

Nope, impulse = mass * velocity. Not velocity divided by mass. You are also not taking the rotational effects into account. E.g. the inertia contribution seen by the impulse at the application point in the direction of the normal. This is sometimes referred to as effective mass.

float EffectiveMassInv = 1/m1 + 1/m2 + dot(n, InvI1 * n) + dot(n, InvI2 * n);
float EffectiveMass = 1 / EffectiveMassInv;

Then you can compute equal and opposite impulses on each body like

float Lambda = EffectiveMass * -RelVelocity;
Body1->ApplyImpulseAt( -n * Lambda, ContactPoint );
Body2->ApplyImpulseAt( n, Lambda, ContactPoint );

 

 

Edited by Dirk Gregorius

Share this post


Link to post
Share on other sites
On 17.10.2017 at 7:56 PM, Dirk Gregorius said:

Nope, impulse = mass * velocity. Not velocity divided by mass. You are also not taking the rotational effects into account. E.g. the inertia contribution seen by the impulse at the application point in the direction of the normal. This is sometimes referred to as effective mass.


float EffectiveMassInv = 1/m1 + 1/m2 + dot(n, InvI1 * n) + dot(n, InvI2 * n);
float EffectiveMass = 1 / EffectiveMassInv;

Then you can compute equal and opposite impulses on each body like


float Lambda = EffectiveMass * -RelVelocity;
Body1->ApplyImpulseAt( -n * Lambda, ContactPoint );
Body2->ApplyImpulseAt( n, Lambda, ContactPoint );

 

 

The OP dont care about rotations, so i havent included it. 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By Alberto Muratore
      Hello, my name is Alberto Muratore and I'm a young game developer specialized in programming.

      Last summer I finished working on Abstract Arena, my first completed project published on Steam. During the development, lasted more than 1 year, I created every aspect of the game except for the audio sector. I previoulsy joined small competitions and had collaborations within the amateur scene, since I started having fun with game development when I was a kid. In the recent months I also started writing videogames reviews for a english-italian website about indie games.

      Abstract Arena Steam page: http://store.steampowered.com/app/678230/Abstract_Arena/
      Abstract Arena website: http://www.abstractarena.com/

          

      I'm currently offering my skills as freelancer in the role of programmer: what I'm searching for is a project that only lacks of the coding part. I'm very good at using the GameMaker: Studio engine, and I already own a license to export on Android platform. I can write code for any genre of 2D games, and I already have experience with the peculiarities of the Android platform (multiple touch controls, accelerometer). I will be able to start working full time only during September, so be aware of that.

      The plan is the following:
      1 - you have an idea about your next project (2D game of any kind, for Windows and/or Android platform),
      2 - you (or your team) create all of the graphics and audio resources,
      3 - I write the whole code for the game (gameplay, menus and anything within the game) putting everything togheter [during September],
      4 - if you like my work you can choose how much to pay for it, and you (or your team) keep the rights to sell the game without sharing any percentage with me.

      Thank you for reading my announcement
      If you have any question, please write me at the following address: albertomurat@gmail.com
    • By N Drew
      I am working on a 2D SideScroller game in my own made game engine using SFML and C++.I am searching for 2D artists,especially pixel artist for making and animating characters,backgrounds and other props that can be made in any Drawing Program.The artist will become part of the team of Hammer Studios and he got a part of the Revenue Sharing.If you are interested send me a mail at:ghiurcutaandrei@gmail.com .If you are not an artist but you want to be a part of our Team,Soon we will be recruiting an C++ AI programmers that worked in SFML/OpenGL.
      We work together using Discord.

    • By JoAndRoPo
      While going through a Game Design Document Template, I came across this heading - Core Game Loop & Core Mechanics Loop. 
      What's the difference? Can you provide some examples of an existing game?  Suppose if I am including these topics in a Game Design Document, how should I explain it so that my team can understand? 
    • By Ds ds
      Hi, my name is Andres, I'm a programmer with a technician degree and a Diploma in C#, looking for a project in Unity to start my career in game development. I don't do it for a paid but a recognition and start a portfolio, preferably a 2D game. Thanks for read, have a nice day. 
       
    • By Doommy
      If someone could assist me through this I would be really grateful. I'm using SharpDX/C#/WinForms but I think this could more apply to directx in general.
      I'm very new to graphics programming and I'm really just trying to do something as simple as displaying a rectangle to the screen.
      Here is my issue:
      I have the below code:
      ----------------------------------------------------------
       var desc = new SwapChainDescription()
                  {
                      BufferCount         = 1,
                      ModeDescription     = new ModeDescription(1024, 768, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                      IsWindowed          = false,
                      OutputHandle        = form.Handle,
                      SampleDescription   = new SampleDescription(1, 0),
                      SwapEffect          = SwapEffect.Discard,
                      Usage               = Usage.RenderTargetOutput
                  };
      I'm not sure if the window is loading in full screen. Actually to make it go full screen I actually have to set the forms property to: this.WindowState        = FormWindowState.Maximized; but that only seems lke Im using a C# code to maximize the form. For instance if I don't set the form to maximize, the form loads at the original size if IsWindowed is set to false. I recall with directx programing using dx7, when I set full screen you could actually see what looked like a display resolution change. I'm not seeing that. It pretty much looks like the form is loaded at the same size as the screen and not the value I provide in modeDescription. This is not what I want as well because I want to set the display to 1024x768 to avoid stretching of my graphics in wide screens.
      Can someone help me make sense of this please.
    • By HomeBrewArcana
      Hey All,
      I'm looking to get into the gaming industry. I've skirted around the idea for a long time, always thinking that I couldn't do it. I've finally decided to take the plunge.
       
      My question is whether it's worth going to school for game design/coding etc. I've been writing content for paper games for a while, and have a good idea of story and some basic design. But I have next to no technical know how. 
       
      My instinct is that such things can be learned with a lot of practice, video tutorials, and more practice. I've also heard that a degree is not really that important, since you get hired based on your portfolio/prototypes. Why not just make the games?
      But won't a degree help with contacts and mentoring--I'm not a great networker.
       
      Of course, it'll plunge me into more debt, but...
      If anyone has advice, let me know. Also any idea of a program to start with: Game Maker, Unity, Godot, Construct, Stencyl--I've heard good things about them all, so much so that I don't know which would be best to start with!
       
      Thanks
    • By bartekm777
      Hello
      About me
      Lvl 28   Programmer (day job: non-gamedev-programmer, making games as a hobby for about 2 years) Some vector art experience - tried to make some assets on my own using vector software and scripts   Some design experience (designing my own games ) About game
      Turn-based fantasy rpg inspired by games like Heroes 3 (also WoG mod), NEO Scavenger, Battle Brothers I would like to create easy to use editor for creating custom scenarios (similar to the one from Heroes 3) World and story are clean slate, I did some drafts but I'm not good at it so it's possibly subject to change I decided to create graphics using vector software + scripts to make it faster (rpg's tend to have lots of assets), also it's more precise and easier to create tileable graphics (for example: rivers, paths) No sound/music work has been done yet Who do I look for?
      Definitely someone with 2d art skills  I would like to focus more on programming 2D animator (skletal animations are preferred) Additional programmer could make development faster Someone for creating sounds/music/both It's a hobby project, I work on it in my free time. In case the project make it to the finish line and get shipped  - I can offer rev-share  
      Below should be few screens of what I already did (about 2 months of work) - some graphics, editor prototype screenshot and game prototype screenshot




    • By Liquifire
      I'm making an small 2D engine using Kha and I have a timer class, which basically simply either waits a certain amount of time to call a function, or repeatedly calls a certain function after every x seconds. I simply want to know if I should have timers run on different threads. I'm aware that makes sense, but I might use many timers in a game for example, would that still be okay? Also I'm currently writing an animation components, which waits every x seconds to draw another image using the timer class. And in a normal 2D games, I would have many objects with animations on them, other than the other timers. So I just wanted to ask people who have more experience and knowledge than I have what I should do for timers: Either leave them on the same main thread, or make them run on different threads. Thanks in advance.
    • By this. games
      [Free]
      Looking For: 2d Artist and Animator.
      Requirements: Experience in 2d art and ability to commit to 1-2 years of work.
      Payment: Rev-Share (Think Free as the product may not end up being sold)
      Description: An 3/4 view 2d game with a Sci-fi style. The game is based on a man who was put into stasis for punishment for his crimes. He has woken up 100 years later and must now regain his position at the top of the criminal underworld by killing his opponents. There will be a "Hub World" city and then PCG gang hideouts where you fight enemies. The assets required will be tile sets for the different hideouts, assets for the city ie buildings streets etc. and characters both the player and a number of enemies.
       
      Send resume and portfolio to thisdotgames@gmail.com if you are interested.
    • By Liquifire
      So I'm making this basic 2D engine using Haxe Kha, and i just need to integrate some physics. Just basic collision detection and gravity on basic shapes, nothing too detailed. But i want to try not to write it myself, so i just want suggestions on what open source phyisics engines i could use, and that wont be impossible to integrate. Thanks in advance.
  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
      631352
    • Total Posts
      2999483
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!