Looking at my previous snipet for reaction of bouncing balls I realise that it is a bit complexed and not very well remarked.
To help newer programmers I am simplifying the code and remarking it.
I plan to show a topic per post in this post I demonstrate how to detect whever or not a collision has occured along a pair of vectors as well as show where the collision is.
This is very accurate at high speeds but not so accurate at low speeds as you'll soon see. My next post will show how to test from front of the ball rather than the centre of the ball.
set text opaque
rem draw a wall to test collision against
wall_start_x = 100
wall_start_y = 100
wall_end_y = 350
wall_end_x = 350
line wall_start_x, wall_start_y, wall_end_x, wall_end_y
rem stage 0 asks for start position
rem stage 1 ask for end position
rem stage 2 calculates the point of collision
text 0,0,"Click the start position of the balls path"
stage = 0
ink rgb(255,0,0), rgb(0,0,0)
do
rem the user defines the start and end postion of balls path using_
rem mouse clicks in the desired location
if stage = 0 and mouseclick() =1
rem get the ball start position when user clicks the mouse for the first time
ball_start_x = mousex()
ball_start_y = mousey()
dot ball_start_x, ball_start_y
stage = 1
text 0,0," "
text 0,0,"Click the end position of the balls path"
wait 500
else
if stage = 1 and mouseclick() = 1
rem get the ball end position when the user clicks the mouse for the secound time
ball_end_x = mousex()
ball_end_y = mousey()
dot ball_end_x, ball_end_y
line ball_start_x, ball_start_y, ball_end_x, ball_end_y
circle ball_start_x, ball_start_y, 8
circle ball_end_x, ball_end_y, 8
stage = 2
text 0,0," "
text 0,0,"Click left mouse button to get location of collision"
wait 500
else
if stage = 2 and mouseclick() = 1
rem on the third mouse click the program calculates the position of a collision
gosub show_collision
wait 500
endif
endif
endif
sync
loop
show_collision:
remstart
this part of the code finds the collision point between the wall
and the balls path and then draws a circle around it
remend
rem get the speed of the ball along the x and y axis
ball_xv# = ball_end_x - ball_start_x
ball_yv# = ball_end_y - ball_start_y
rem get the x and y difference from start to end of wall
rem the x length and y length if you like
wall_xv# = wall_end_x - wall_start_x
wall_yv# = wall_end_y - wall_start_y
rem now understanding how this next part works is not important
rem just know that this is the collision test basically it calcs s and t
rem if s and t are between 0 and 1 then there has been a collision
s# = ((0-ball_yv#) * (ball_start_x-wall_start_x) + ball_xv#*(ball_start_y-wall_start_y)) / ((0-wall_xv#)*ball_yv# + ball_xv#*wall_yv#)
t# = (wall_xv# * (ball_start_y-wall_start_y) - wall_yv# * (ball_start_x-wall_start_x)) / ((0-wall_xv#)*ball_yv# + ball_xv#*wall_yv#)
if (s# >=0 and s# = 0 and t#