UnderwareDESIGN

PlayBASIC => Resources => Source Codes => Topic started by: kevin on July 07, 2005, 03:12:31 PM

Title: Calc Ray Reflections
Post by: kevin on July 07, 2005, 03:12:31 PM
This is a bit of quick hack to the ray intersection example.  Figured you might like to know how to calc the angle of reflection.   So here it is


[pbcode]

   WorldWidth=GetScreenWidth()
   WorldHeight=GetScreenHeight()

; create a Camera
   CreateCamera 1

; Create world
   CreateWorld 2
   CaptureToWorld 2

; draw a series of boarder line for this world
   Dot 0,0
 line 0,0,worldwidth,0
 line worldwidth,0,worldwidth,worldheight
 line worldwidth,worldheight,0,worldheight
 line 0,worldheight,0,0

; draw a series of polygon shaped obejct into the world
 for lp=1 to 10
    xpos#=50+rnd(worldwidth-100)
    zpos#=50+rnd(worldheight-100)
    size=rndrange(30,100)
    angle=rnd(359)
    Make_Convex(rndrange(3,20),xpos#,zpos#,Size,angle)       
 next lp

; Partition The world up into 32 by 32 cells
   PartitionWorld 2,32
   
; Tell PB to return to Immediate drawing mode
   DrawGfxImmediate


; statrt of DO/Loop
   Do
   ; capture to scene and grab the world info
 CaptureToScene
 ClsScene
 capturedepth 100
 CameraGrabWorld 1,2

 
   ; Get the mouse position
 mx#=mousex()
 my#=mousey()

   ; Cast 150 rays out fomr the mouses position
 rays=50
 For Ray=1 to Rays
    angle#=(360.0/Rays)*Ray  
    x2#=cosnewvalue(mx#,angle#,300)
    y2#=sinnewvalue(my#,angle#,300)
    if RayIntersectWOrld(2,mx#,my#,x2#,y2#)=true
      x2#=getintersectx#(0)
      y2#=getintersecty#(0)
      nx#=getnormalx#(0)
      ny#=getnormaly#(0)

      capturedepth 10
      circlec x2#,y2#,3,1,rgb(255,0,0)

   ; Calc reflection Direction
      WallAngle#=AtanFull(ny#,nx#)
      RayAngle#=GetAngle2d(x2#,y2#,mx#,my#)
      ReflectAngle#=WrapAngle(WallAngle#,WallAngle#-RayAngle#)
      
      x3#=cosnewvalue(x2#,ReflectAngle#,50)
      y3#=sinnewvalue(y2#,ReflectAngle#,50)
      linec x2#,y2#,x3#,y3#,rgb(255,255,0)

    endif
    capturedepth 20
    line mx#,my#,x2#,y2#

 next

; draw the camera  
 DrawCamera 1

; show the fps rate and continue this loop
 text 0,0,fps()
 sync
   loop
   

; This function creates a convex polygon shape

Function Make_Convex(edges,xpos#,ypos#,Size,angle)
 sa#=360.0/edges
 c=rndrgb()
 for lp=0 to edges-1
    a#=angle+(lp*sa#)
    x1#=xpos#+cosRadius(a#,size)
    y1#=ypos#+SinRadius(a#,size)
    if lp<(edges-1)
   a#=angle+((lp+1)*sa#)
    else
   a#=angle
    endif
    x2#=xpos#+cosRadius(a#,size)
    y2#=ypos#+SinRadius(a#,size)
    line x2#,y2#,x1#,y1#
 next lp
endfunction i


[/pbcode]