Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

Code Snippets / [DBP] - perfect 2D bullet collision detecting function

Author
Message
noobnerd
12
Years of Service
User Offline
Joined: 30th Nov 2010
Location:
Posted: 6th Nov 2011 20:11
I stumbled upon this problem while i was making my 2D freelance game ( WIP ). the problem was that when i had bullets that moved very fast, they sometimes just flew over the enemy instead of impacting.
At this time i was using the basic pythagoras theorem to get the distance between target and bullet and check if that was lower than the targets radius.

the new method is more complex, it checks if the bullet and target have been within range during the last "frame" using simple maths. ( it doesnt iterate anything )

the result is that you can have bullets of any velocity!

possible uses :
-to check bullet collision ( DUH )
-if you set the bullet velocity to fast enough this can be used as a 2D raycast
-it can easily be modified to get the coordinates.

and the code :

where x1#,y1# are the coordinates of either the bullet or the enemy
xv1# and yv1# the x and y velocities of the bullet or the enemy
(remember that x1#,y1#,xv1# and yv1# must be of the same entity ! )
and ofcourse x2#,y2#... are the same but for the other one
r# is the radius of the target
( if your bullet also has a radius then add that and the targets radius together here )




this function will return a 1 if it was a hit and 0 if it wasnt

use it like this

if advbullethit(enemyx#,enemyy#,enemyxv#,enemyyv#,bulletx#,bullety#,bulletxv#,bulletyv#,enemyradius#+5) = 1 then dec enemyhp#,bulletdamage#

how to get x and y velocity ?
very easy with vectors, otherwise like this :

ox# = x# : oy# = y#
x# = x#+4 : y# = y#+3 ' player moves 4 along the x and 3 along y
xv# = x#-ox# : yv# = y#-oy#

Login to post a reply

Server time is: 2022-11-30 14:27:24
Your offset time is: 2022-11-30 14:27:24