I need to make a correction in the reflection equation.
a = a - 2*(a*n)*n
(a*n) is really suppose to be
a dot product b. Here's the new code.
REM ==================================|
REM Vector reflection example |
REM By: Phaelax |
REM ==================================|
REM Reflection equation is: |
REM B = A - 2(A.N)N |
REM where '.' represents dot product |
REM ==================================|
set display mode 1024,768,32
sync on
rem ray of incident
null = make vector2(1)
rem normal vector
null = make vector2(2)
rem the reflective plane/surface/line
px1 = 0
py1 = 400
px2 = screen width()
py2 = 200
REM x2,y2 represents the point of impact on the surface(or plane) from the ray
REM in this case, the center of the line
x2 = screen width()/2
y2 = 300
do
cls
rem reflection plane or surface
ink rgb(0,255,0),0
line px1,py1,px2,py2
rem reflection surface's normal
rem we divided by the length of the line so we can have normalized values
d# = sqrt((px2-px1)^2+(py2-py1)^2)
nx# = (py1-py2)/d#
ny# = -(px1-px2)/d#
line x2,y2,x2+nx#*20,y2+ny#*20
rem control angle of incident with mouse
x1 = mousex()
y1 = mousey()
rem draw the incoming ray
ink rgb(255,255,255),0
line x1,y1,x2,y2
rem length of incoming ray
d# = sqrt((x2-x1)^2+(y2-y1)^2)
rem calculate reflection vector
ax# = (x2-x1)
ay# = (y2-y1)
set vector2 1,ax#, ay#
set vector2 2, nx#,ny#
r# = dot product vector2(1,2)
ax# = ax# - 2*r#*nx#
ay# = ay# - 2*r#*ny#
rem draw the reflected ray
ink rgb(255,0,0),0
line x2,y2,x2+ax#*d#,y2+ay#*d#
sync
loop
I didn't catch the bug right away because it doesn't present itself when the reflective surface is axis-aligned, as in what demo used.