Collision Detection Part-1

Introduction
This tutorial is an introduction about collision detection and in this first part we will see how to detect collision between two circles. I will be using Python programming language to write the code and hope you are already familiar with Python language 🙂

Collision between two circles
Here we will take two circles as our input, for each circle we will take the position and radius. Using this three values from each of the circle we can easily check the collision.

  • Calculate the horizontal distance between the circle centers
  • Calculate the vertical distance between the circle centers
  • Form a right angle triangle using the horizontal distance as base and vertical distance as height
  • Calculate the length of the hypotenuse using the base and height
  • Calculate the distance between the center of the circles
  • If hypotenuse calculated is less than the distance between the center of the circles we can say a collision occurred.

The below given image describes three different cases of collision between two circles

collision

How can we make use of the circle collision detection
Consider two objects having random shapes and you have to do some collision collision check between this two objects. Yes the exact collision detection between random shaped objects are not easy to achieve. But you can do the collision detection between this two with circles

  • Define a mask for each of the shapes. Let the mask be a circle of a specific radius. The radius selected should be enough to cover (at least 80%) the random shaped object. Do the same for the second object
  • Now all you have to do is processing this mask while checking collision. Since the mask defined for each object is circular in shape and cover 80% of the area, the collision checking will be easy and enough. 🙂

The Program
The below given program is written in Python language and the things that we saw above is written step by step.

import math

# Find the absolute value of a variable
def absolute_value(x):
    if x < 0:
        return 0 - x
    return x

# Read parameters of a circle, x_position, y_position and radius
def read_circle(number):
    radius = int(input("Enter circle " + str(number) + " radius: "))
    x_position = int(input("Enter circle " + str(number) + " x position: "))
    y_position = int(input("Enter circle " + str(number) + "y position: "))
    print()
    return (radius, x_position, y_position)

# Create a right angle triangle and check for collision
# Take two circles as arguments and do the calculation
def check_collision(circle1, circle2):
    base = absolute_value(circle1[1] - circle2[1])
    height = absolute_value(circle1[2] - circle2[2])
    hypotenuse = math.sqrt(base * base + height * height)
    center_distance = circle1[0] + circle2[0]
    if hypotenuse <= center_distance:
        return True
    return False

# The main method
# Print success message on collision
def main():
    circle1 = read_circle(1)
    circle2 = read_circle(2)
    
    collision_status = check_collision(circle1, circle2)
    if collision_status:
        print("Success")
    else:
        print("Failed")

main()

Hope this tutorial was helpful 🙂

Thanks for Reading

Creating Slide Show using Java

Today i was doing some search in my personal computer prior to formatting the hard disk and to take backup of important files and I came across a small java source code file. I wrote this code during my collage days and did it as part of the technical exhibition conducted by my college. As part of it I got a chance to prepare some presentation on game development basics and created some slides. All I wanted was to run this slides (images) in an equal interval of time, so it will run continuously in circular fashion without any user intervention. The program will load the predefined images using the file name and display it for three seconds and move it to next image. After reaching the the last image, it will start again from the first image. I would like to share the code here 🙂

Source Code

import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

class JavaSlider extends JPanel implements Runnable {
	
	private Thread sliderThread;
	private boolean active;
	private JFrame parent;
	
	public JavaSlider(JFrame parent) {
		super();
		sliderThread = new Thread(this);
		active = false;
		println("Panel created...");
		this.parent = parent;
	}
	
	public void setActive(boolean status) {
		println("Thread activated/deactivated...");
		active = true;
	}
	
	public Thread getThread() {
		return sliderThread;
	}
	
	public void start() {
		setActive(true);
		println("Thread started...");
		sliderThread.start();
	}
	
	@Override
	public void run() {
		int counter = 1;
		String name = "";
		while (active) {
			try {
				name = "slide" + counter + ".png";
				println("Loading file " + name + "...");
				BufferedImage image = ImageIO.read(getClass().getResource(name));
				println("Loaded file " + name + "...");
				parent.setSize(image.getWidth() + 4, image.getHeight() + 32);
				getGraphics().drawImage(image, 0, 0, image.getWidth(), image.getHeight(), this);
				if (++counter > 23) {
					println("Reseting counter...");
					counter = 1;
				}
				Thread.sleep(3000);
			} catch (IOException | InterruptedException ex) {
				println("Interrupted...");
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		JFrame frame = new JFrame("Java Slider");
		JavaSlider panel = new JavaSlider(frame);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(960, 720);
		frame.setContentPane(panel);
		frame.setResizable(false);
		frame.setVisible(true);
		frame.setLocation(0, 0);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				panel.setActive(false);
			};
		});
		panel.start();
		panel.getThread().join();
	}
	
	public static void println(String message) {
		System.out.println(message);
	}
}

Developing a Mini Calculator Part-2

Hello, this is a continuation of article on Developing a Mini Calculator Part-1. In the first part I have explained about the components required for this application. Today we will see the implementation of Calculation Logic.

Note: I will be using Java programming language to demonstrate the examples

Calculation Logic

Since our calculator only support four operations and each of them take two operands and one operator it will be easy for us to write one single procedure or method which do all the necessary operation and return the result

public static double doCalculate(double operand1, char operator, double operand2) {
    double result = 0.0;
    switch (operator) {
        case '+': result = operand1 + operand2; break;
        case '-': result = operand1 - operand2; break;
        case '/': result = operand1 / opernad2; break;
        case '*': result = operand1 * operand2; break;
    }
    return result;
}

The above given method is seems good but what will happen if you divide a number with zero. Yes of course division by zero is not possible. In that case what we will do. One way is to insert an error handling code that do the required when such and error comes. Again think of other scenario where the result is infinity or not a number. What we will do again insert some logic to handle that scenario.

Instead of keeping all calculations in one method we can separate them, like one method for addition, one four subtraction etc. Each of them will take three arguments and return the expected result.

public static double doCalculate(double operand1, char operator, double operand2) {
    double result = 0.0;
    switch (operator) {
       case '+': result = doAddition(operand1, operand2); break;
       case '-': result = doSubtraction(operand1, operand2); break;
       case '/': result = doDivision(operand1, operand2); break;
       case '*': result = doMultiplication(operand1 * operand2); break;
    }
    return result;
}

private static double doAddition(double operand1, double operand2) {
    return (operand1) + (operand2);
}

private static double doSubtraction(double operand1, double operand2) {
    return (operand1) - (operand2);
}

private static double doDivision(double operand1, double operand2) {
    return (operand1) / (operand2);
}

private static double doMultiplication(double operand1, double operand2) {
    return (operand1) * (operand2);
}

Now we can manage each operation logic separately, say for division we can add extra error handling code

private static double doDivision(double operand1, double operand2) {
    double result = 0.0;
    try {
        result = operand1 / operand2;
    catch (ArithmeticException ex) {
        // set some flag to indicate this error
    }
    if (new Double(result).isNaN()) {
        // set some flag to indicate this
        result = 0.0;
    } else if (!Double.isFinite(result)) {
        // set some flag to indicate this
        result = 0.0;
    }
    return result;
}

If we look at the above program we will see two things. If the division leads to error we will set some flag and return zero. If the result is not a number or infinite we do the same. The flag might be some where else in the program. We have to introduce a state change some where out side the calculation logic. This is okay! because it doesn’t harm anything.

Instead of changing the state out side the calculation logic we can simply return the entire result out side the calculation logic. Say, the result, is it valid?, is it infinite?, is it an error. How we will do this?

public class Result {
    private double value;
    private boolean error;
    private boolean finite;
    private boolean nan;
    
    public Result() {
        // initialize to default
    }
    // get and set methods will come here
}

We can create a new Result object to do this. This object will keep all the information related to the operation carried out. The Calculation Logic simply return the final result with necessary information to process the result. So an external module say Core can process the result as required without worrying about the calculations 🙂

Calculation Logic: Do the required calculations and return the result
Core: Process the result and take the necessary actions

private static Result doDivision(double operand1, double operand2) {
    Result result = new Result();
    double value = 0.0;
    try {
        value = operand1 / operand2;
    catch (ArithmeticException ex) {
        result.setError(true);
    }
    result.setValue(value);
    if (new Double(value).isNaN()) {
        result.setNaN(true);
    } else if (!Double.isFinite(result)) {
        result.setFinite(false);
    }
    return result;
}

Here ends the second part. Hope you like it 🙂

In the next part we will see the implementation of other modules.