News:

Building a 3D Ray Tracer  By stevmjon

Main Menu

Vector based bounce

Started by programaths, January 30, 2021, 10:35:55 AM

Previous topic - Next topic

programaths

When you are a student, you often ask how useful are math.

This example shows basic use of vectors to compute a bounce.
There is no need for trigonometric functions!

The code below make use of the following:

  • Vectors
  • Normals (yes, a vector)
  • Dot product
  • Thales theorem

Also, the dot product permits to know if two vectors are looking in the same direction.
When their normalized version are aligned, it return 1.
When their normalized versions are opposed, it return -1.
A value of 0 indicate they are orthogonal (perpendicular).


PlayBASIC Code: [Select]
; PROJECT : VectorBounce
; AUTHOR :
; CREATED : 1/30/2021
; EDITED : 1/30/2021
; ---------------------------------------------------------------------


; A line, but that could be any shape
s=newShape(2,1)
setShapeVertex s,0,0,0
setShapeVertex s,1,200,200
SetShapeEdge s,0,0,1


do
cls

; Draw the shape which will receive the bounce
drawshape s,200,200,3

x=mousex()
y=mousey()

; circle at the mouse location
circle x,y,4

; fixed circle which represent a fixed aim
circle 250,350,4

; line between the two circles
line x,y,250,350

; compute the hit between the shape and our "ray"
if lineHitShape(x,y,250,350,s,200,200,1)
ix#=getIntersectx#(0)
iy#=getIntersecty#(0)
nx#=getNormalX#(0)
ny#=getNormalY#(0)

; blue circle representing the hit location
circleC ix#,iy#,4,1,$0000ff
; compute the distance between ray origin and hit location
dist#=float(getDistance2d(x,y,ix#,iy#))

; normalize the vector to be used in dot product
nix#=(float(x)-ix#)/dist#
niy#=(float(y)-iy#)/dist#

; compute the dot product of two normalized vectors.
; This gives the length of one projected on the other.
dotp#=nix#*nx#+niy#*ny#

; scale the normal by the distance which is scaled by the length of the projection
; See Thales
symx=ix#+nx#*dotp#*dist#
symy=iy#+ny#*dotp#*dist#

; red circle representing the symmetry point
circleC symx,symy,4,1,$ff0000

; compute the target location
tx=x+2*(symx-x)
ty=y+2*(symy-y)

; green circle representing the target location
circleC tx,ty,4,1,$00ff00

; yellow line representing the "bounce"
lineC ix#,iy#,tx,ty,$ffff00

endif

sync

loop