Sometimes find book suggestions too hard - how would I go about implementing this (collision)

edited February 2015 in Questions about Code

I'm not sure how to do this, here's the suggestion :

I'll paste the code at the bottom of this post.

But I don't know how to go about doing the collision. I can think about what I need, and that is the coordinates of all ball objects so that one can tell if it hits the other. I don't have a clue where to start with this though.

To try and make things a bit easier I've made a Minimal Working Example with just two balls. I'm still unsure how to detect the collisions between objects though. (The collisions with the screen edge are a bit dodgy as well tbf )

I'm not sure how to handle it though, I thought that I might be able to make a detect function or something but it's just made the balls shiver up and down.

So I'm not too sure what to do, the basic thinking was that I could make detect read the x coordinates of the two objects and reverse the speed values when they were close / touching. But this just makes them freeze, which kind of makes sense as I guess they're cancelling each other out constantly and staying in the same position.

void setup() {

  size(300, 300);
  b = new ball(100, 100, 50, color(100, 1, 240));
  b1 = new ball(100, 100, 50, color(100, 212, 40));
ball b, b1;
void draw() {

class ball {
  float x, y, s;
  float speedx = random(1, 5.5);
  float speedy = random(1, 6);
  color c;
  ball(float x, float y, float s, color c) {
    this.x = x;
    this.y = y;
    this.s = s;
    this.c = c;

  void detect(ball t) {
    if (abs(x-t.x)<5) {
      speedx *= -1;

  void display() {
    ellipse(x, y, s, s);

  void move() {
    x += speedx;
    y += speedy;

    if (x > width - s) {
      x = width-s;
      speedx *= -1;
    if (x < s ) {
      x = s;
      speedx *= -1;

    if (y > height - s) {
      y = height-s;
      speedy *= -1;
    if (y < s) {
      y = s;
      speedy *= -1;
Sign In or Register to comment.