2d vector to 2d direction normal, and movement speed, example

Started by RemiD, December 02, 2022, 11:15:55

Previous topic - Next topic

RemiD

an example for beginners...


;2d vector to 2d direction normal, and movement speed, example by RemiD (20221202)
;this demonstrates the difference between a 2d vector (of any direction and any length).
;and a 2d direction normal (= normalized vector) which can point in any direction but with always a length of 1.
;and then it is possible to give a direction to the entity, but also give it movement speed with another speed variable.

Global gwidth% = 640 : Global gheight% = 480
Graphics(gwidth,gheight,32,2)

SeedRnd(MilliSecs())

;2d vector properties
Global Vx# : Global Vy#

;2d direction normal properties
Global Nx# : Global Ny#

;movement speed variable
Global Speed#

Goto ChooseVectorProperties

Repeat

If( MouseHit(1)=1 Or KeyHit(57)=1 )

  .ChooseVectorProperties
  ;define another 2d vector
  Vx# = Rnd(-1,+1) : Vy# = Rnd(-1,+1)
  ;calculate vector length
  VLength# =  Sqr( ( Vx * Vx ) + ( Vy * Vy ) )
  ;calculate direction normal corresponding to this vector
  Nx = Vx / VLength : Ny = Vy / VLength
  ;define another speed value
  Speed = 4 ;Rand(1,8)

EndIf

SetBuffer(BackBuffer())
ClsColor(000,000,000) : Cls()

;draw the 2d vector
Color(125,125,125) : Line( 160+0, 240+0, 160+Vx*10, 240+Vy*10 ) ;*10 is to better see the line, for debuging
Rect( 160+0-1, 240+0-1, 3, 3, True )

;draw the 2d direction normal
Color(250,000,250) : Line( 320+0, 240+0, 320+Nx*10, 240+Ny*10 ) ;*10 is to better see the line, for debuging
Rect( 320+0-1, 240+0-1, 3, 3, True )

;draw the 2d translation vector (2d direction normal * speed)
Color(250,250,250) : Line( 480+0, 240+0, 480+Nx*Speed*10, 240+Ny*Speed*10 ) ;*10 is to better see the line, for debuging
Rect( 480+0-1, 240+0-1, 3, 3, True )

Flip()

Until( KeyHit(1)=1 )

End()