1

I made this small game similar to flappy birds, where one can use to fly up and down using the mouse and keyboard.

I won't be posting the full code because it's a university project and I don't want to get caught for any possible plagiarism.

What I did was, I used two objects:

A rectangle as the bird:

r= rectangle('Position', pos, 'curvature', [0.99,0.1], 'FaceColor', 'r', 'EraseMode','xor');

Thick lines to represent the walls:

line([ 100 100], [10 400], 'color', 'm', 'LineWidth', 10, 'EraseMode', 'background')

My problem:

The problem is that the bird moves through the walls, as if the walls were transparent. As you can imagine, I want to break the game and show something like "game over", when the bird hits the wall (not go through them). How do I make it such that my game breaks when the bird (object 1) collides with the walls (other objects)?

Thank You Very Much for reading my question!

The Artist
  • 213
  • 1
  • 2
  • 7

2 Answers2

2

You'd want to use an intersection algorithm to check whether there is an intersection of one of the wall-lines (check it four times) with the rectangle. The rectangle basically also consists of 4 lines, that means you should check the 4 rectangle-lines against the four wall-lines (if you use a line-line-intersection algorithm).

E.g. check this topic: How to find the intersection point between a line and a rectangle?

It's basically a simple mathematical equation to solve, see https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection.

tim
  • 9,896
  • 20
  • 81
  • 137
2

If you have the Mapping Toolbox installed, it provides a function called polyxpoly that allows you to intersect polylines, so you can find the intersection of the whole rectangle against every wall, and you will not have to worry about splitting every edge of the rectangle.

Here you have a full working example of a collision with one wall:

% Bird (rectangle).
% Position.
xr = 30;
yr = 100;

% Length of rectangle edges.
deltaxr = 10;
deltayr = 10;

% Vector for rectangle object.
vr = [xr, yr, deltaxr, deltayr];

% Bird polyline.
a = [xr, yr];
b = [xr + deltaxr, yr];
c = [xr + deltaxr, yr + deltayr];
d = [xr, yr + deltayr];
r = [a; b; c; d];

% Wall (line).
% Wall polyline.
l = [40 0; 40 105];

% Draw objects.
r1 = rectangle('Position',vr,'LineWidth',2);
line(l(:,1), l(:,2),'LineWidth',2,'Color','r');
axis equal;

% Find intersections.
[xi,yi] = polyxpoly(r(:,1),r(:,2),l(:,1),l(:,2));

% Are there any intersections? If so, GAME OVER.
if ~isempty(xi)
    % Stop the game and display GAME OVER.
    text(xr-20,yr-20,'GAME OVER','Color','b','FontSize', 20);
end

You can try with different positions of the bird to test the collision detection:

Collision detection flappy bird

codeaviator
  • 2,545
  • 17
  • 42