Creating collision

Hello /sub

I’ve been trying to create a simple game based on different classes. However, i’m currently at a dead end, since i’m trying to create a collision detector between the player class and the asteroid class.

However, do i have to detect the collision outside the classes, in either setup or draw for it to work? I wanted to implement the collision inside one of the classes.

How would i create this collision dectection? I wanna know, if one of the asteroid rectangles overlap the player rectangle.

You can check the source code and run the application on:

I would do the for loop outside the classes in draw(). You for loop over all asteroids here.

But you can have a function in the asteroid class isColliding to check its distance to the player and return a boolean variable for yes/ no.

The collision detection itself: use if(dist(…)< 30) …

See reference for dist

As @Chrisir mentioned, it’s best to place the loop outside the involved classes.

The collision detection part can be turned into a method inside 1 or both classes.

For example, the sketch from the link below got a method named gotStick() inside class Beaver w/ a Stick parameter, which checks whether whether the current Beaver is colliding w/ the passed Stick:

boolean gotStick(Stick s) {
  return x+SIZE > s.x & x < s.x+Stick.W & y+SIZE > s.y & y < s.y+Stick.H;

Extra info about rect-to-rect collision algorithm:

Great! The gotStick example made great sense to me. And that was excatly what i was looking for. Thanks alot :slight_smile:

Now i can just call the method inside the for loop checkCollision(m1[i])

1 Like