This is a simple, but working implementation of a collision_triangle function. It is meant to mimic built-in collision_* functions.


The syntaxis is as follows:

collision_triangle(x1, y1, x2, y2, x3, y3, obj, prec, notme)

The first 6 variables are the coordinates of the triangle, and obj is the object to be looked for. The script can handle both id’s and object indices. precise works the same as any other collision_ function: whether the bounding box should be used (false) or the sprite (true). notme signals whether to check for the instance from which the script is called as well.


There are a couple of things that are important. First of all you will also need to add this script from GMLScripts. Note: it looks like version 1.3 will include this script by default. However. This function has the arguments in a slightly different order, rather than first taking the 3 triangle coordinates, followed by the test point, it first takes a test point, and then the 3 triangle coordinates. You will have to edit the script below to fix this problem. Just move the last two arguments from each point_in_triangle to the front.

Secondly, this image is also important:

super important image

Super important image

The origin of the sprite is supposed to be on the sprite itself. You won’t recieve any error messages if this is not the case, but the function could return incorrect results.


Finally, here it is:


var xx, yy, coll_line;

xx[1] = argument[0];
yy[1] = argument[1];
xx[2] = argument[2];
yy[2] = argument[3];
xx[3] = argument[4];
yy[3] = argument[5];

coll_line[1] = collision_line(xx[1], yy[1], xx[2], yy[2], argument[6], argument[7], argument[8])
if (coll_line[1] != noone) return coll_line[1];

coll_line[2] = collision_line(xx[2], yy[2], xx[3], yy[3], argument[6], argument[7], argument[8])
if (coll_line[2] != noone) return coll_line[2];

coll_line[3] = collision_line(xx[3], yy[3], xx[1], yy[1], argument[6], argument[7], argument[8])
if (coll_line[3] != noone) return coll_line[3];

with (argument[6])
  if (point_in_triangle(xx[1], yy[1], xx[2], yy[2], xx[3], yy[3], x, y) && argument[8] != id)
  return id;

return noone;

Feel free to ask a question or leave a comment below.

Leave a Reply

Name and website fields are completely optional.