Intercept a vector

BlitzMax Forums/BlitzMax Programming/Intercept a vector

siread(Posted 2007) [#1]
I want my object (a player) to intercept a vector (a ball). Rather than move directly towards the ball's current position or ultimate destination I want it to intercept it at the shortest possible distance. How do I calculate the angle that the player should take?


Neraj(Posted 2007) [#2]
I wrote a function for that you could use. Its written in blitz3d, so perhaps you have to alter the syntax a little.

The function does return a type, the first 3 variables are the position of the intersection, so its the position you have to move your player to, the"h" tells wether you can intercept or not (0 if you can't, 1 if you can)

Type ZielVektor
Field x#,y#,z#,h
End Type

The function needs to know where you are (ax,ay,az) how fast you are (v), where the target is (zx,zy,zz) and how the target is moving (vx,vy,vz)


Function zielen.ZielVektor(v#, ax#, ay#, az#, zx#, zy#, zz#, vx#, vy#, vz#)

Local treffer = 0
Local l2#=-1
Local l1#=-1
Local lw#=0

Local a#=v#^2-vx#^2-vy#^2-vz#^2
Local b#=-2*(zx#-ax#)*vx#-2*(zy#-ay#)*vy#-2*(zz#-az#)*vz#
Local c#= -1*(zx#-ax#)^2-1*(zy#-ay#)^2-1*(zz#-az#)^2

If a#=0 Then
If b#=0 And c#=0 Then l1#=0
If b#<>0 Then l1#= -1*c#/b#
Else
If b#^2>=4*a#*c# Then l1#=(-b#+(b#^2-4*a#*c#)^0.5)/(2*a#): l2#=(-b#-(b#^2-4*a#*c#)^0.5)/(2*a#)
End If

If l1#>=0 Then lw# = l1#:treffer=1
If l2#>=0 Then lw# = l2#:treffer=1

z.ZielVektor = New ZielVektor
z\h=treffer

If treffer = 1
z\x#=zx#+lw#*vx#
z\y#=zy#+lw#*vy#
z\z#=zz#+lw#*vz#
End If

Return z

End Function

It will be hard to understand from the code what the function does (no comments, variable names very short or in german...) I have written it to calculate where my enemies have to aim with their projectiles to hit their target.
If you wish i can explain the math a little further, its just simple vector geometry.

edit: i made a mistake in the description of the type, you better read it again if you have read it before the edit ;-)