Simple Raycast for GMS
A downloadable asset pack
It's a simple raycast script to use your game projects. You can check objects, tilemaps or both with this script.
Note: Supports v2.3 and higher version
FEATURES
- It supports a specific object, multiple objects, tilemap layers or all at the same time.
- It works with different collision shapes. ( Set to _precise_mode as true to do that.)
- I added comments in the script if you want to learn how it works.
- You need only one method.
- Flexible to use in all your projects.
What is the Raycasting?
Raycasting is the process of sending a ray during simulation and detecting the object that collides with it.
Why would I use it?
This is a very important function for 2d games. This process is most often used for bullet collisions, advanced character controller, the enemy AI...
How can I use this?
The method is simple.
raycast(_x,_y,_dir,_length,_per_pixel,_object,_tilemap_layer_name,_precise_mode)
_x: int-The start x position of the ray
_y: int-The start y position of the ray
_dir: int-The direction of the ray (angle)
_length: int-The length of the ray (pixels)
_per_pixel: int-Checking collisions per this defined pixels
_object: index-Object id or object array (like this [object01,object02...] ) It's an optional argument and the default value is **all**. If you don't want to use it, use "noone" key for this.
_tilemap_layer_name: string- Target tilemap layer name with a string type. It's an optional argument. If you don't want to use it, use "noone" key for this.
_precise_mode: boolean-Precise Mode required when you use collision mask shapes except the square on the objects. It's optional argument and default value is false.
The method returns a data struct.
raycast_data
|
|->type: enum- rc_type.nothing , rc_type.tilemap or rc_type.object
|->index: int- instance id or tilemap index
|-> x: int - x position of the ray collision point
|->y: int - y position of the ray collision point
Samples
//A sample for tilemaps and all of objects; my_raycast_data=raycast(x,y, 45, 100 ,16 ,all,"Tiles_Collider",true); //A sample for some objects; my_raycast_data=raycast(x,y, 45, 100 ,16 ,[object_blue,object_pink]); //A sample for a specific object my_raycast_data=raycast(x,y, 45, 100 ,16 ,object_blue);
Checking raycast with a simple way;
if(my_raycast_data.type!=rc_type.nothing){ var raycast_pos_x=my_raycast_data.x; var raycast_pos_y=my_raycast_data.y; if(my_raycast_data.type==rc_type.object){ var collided_object=my_raycast_data.index; //Do something }else if(my_raycast_data.type==rc_type.tilemap){ var collided_tile_index=my_raycast_data.index; //Do something } //More codes... }
Note: It's just a sample to beginners to see how it works. But I recomend to use switch-case statement instead of if-else for this kind of thing. Still the choice is yours.
Purchase
In order to download this asset pack you must purchase it at or above the minimum price of $3 USD. You will get access to the following files: