Programming by Example

 

A BB4W Compendium

freeman69@gmx.com

IDIC BBC_Owl2 M&P

Vector Demo

A vector is often derived from two points e.g. from point 'a' to point 'b', where 'a' and 'b' have co-ordinates x,y (or x,y,z in three dimensions). To find the vector from 'a' to 'b' we subtract b - a. The vector from 'b' to 'a' would be a - b.

 

Having a direction allows us to find the angle (theta) between two different vectors using something called the 'dot product' in the formula a.b=|a||b|cos(theta). Where a.b is the dot product of 'a' and 'b', and |a| is the magnitude of 'a'.

 

  10 MODE 9:OFF

  20 *REFRESH OFF

  30 *FONT Arial,16

  40

  50 angle=0:r=300

  60 REPEAT

  70   TIME=0:CLS

  80   PRINTTAB(1,1)"Vectors are the difference between 2 pairs of co-ordinates"

  90   PRINTTAB(1,2)"and can be used to calculate helpful things..."

 100  

 110   angle+=1

 120   x=640

 130   y=320

 140   linx=x+SIN(RAD(angle))*r

 150   liny=y+COS(RAD(angle))*r

 160   LINE x,y,linx,liny:REM Solid line

 170  

 180   MOUSE mx,my,mz

 190   MOVE x,y:PLOT 37,mx,my:REM Dashed line

 200  

 210   veclinx=linx-x

 220   vecliny=liny-y

 230   vecmx=mx-x

 240   vecmy=my-y

 250  

 260   a=FNanglebetween(veclinx,vecliny,vecmx,vecmy)

 270  

 280   REM  N.B. To find the 'normal' of a vector

 290   REM  rotate left by 90 degrees: x becomes -y, y becomes x

 300   MOVE x,y:PLOT 21,x-vecliny/2,y+veclinx/2:REM Dotted line

 310   REM 'Dot product' = x1*x2+y1*y2

 320   b=-vecliny*vecmx+veclinx*vecmy

 330  

 340   IF b<0 side$="right":amount$="more" ELSE side$="left":amount$="less"

 350   PRINTTAB(1,4)"Mouse is to the "+side$+" of solid line by ";INT(a);" degrees."

 360   PRINTTAB(1,5)"(Mouse is "+amount$+" than 90 degrees from dotted line)"

 370  

 380   *REFRESH

 390   WAIT 4-TIME

 400 UNTIL FALSE

 410 END

 420

 430 DEF FNanglebetween(x1,y1,x2,y2)

 440 LOCAL m1,m2

 450 IF x1=x2 AND y1=y2 THEN

 460   =0

 470 ELSE

 480   m1=SQR(x1^2+y1^2)

 490   m2=SQR(x2^2+y2^2)

 500   REM 'Dot product' = x1*x2+y1*y2

 510   =DEG(ACS((x1*x2+y1*y2)/(m1*m2)))

 520 ENDIF

Arrow black large Arrow black large