reflecting a vector

Blitz3D Forums/Blitz3D Beginners Area/reflecting a vector

Steven Noyce(Posted 2006) [#1]
This is more of a math question than a programming question, but I just can't figure this out. Eventually, what I am trying to do is get a ball to bounce off any surface that it hits corectly, but for now, what I realy want is a simple little program that you type in the vector of the surface and the vector of the ball, and it prints the resulting vector of the ball after it hits the surface and is reflected.

I know that I am kind of saying "write my program for me", but I just want a simple program, and I don't think this would take someone who knows how to do this very long.

Thanks in advance! Please help!


mindstorms(Posted 2006) [#2]
I used the distance equation in this little game (also in code archives...Doesn't use true vectors but I think it will help.




mindstorms(Posted 2006) [#3]
If you are working in 3d, this code from the code archives might help...It requires blitz collisions.

For i = 1 To CountCollisions(entity)
	; Calculate bounce: 

	; Get the normal of the surface collided with. 
	Nx# = CollisionNX#(entity, i) 
	Ny# = CollisionNY#(entity, i) 
	Nz# = CollisionNZ#(entity, i) 
	
	; Compute the dot product of the ball's motion vector and the normal of the surface collided with. 
	VdotN# = xvel#*Nx# + yvel#*Ny# + zvel#*Nz# 
	
	; Calculate the normal force. 
	NFx# = -2.0 * Nx# * VdotN# 
	NFy# = -2.0 * Ny# * VdotN# 
	NFz# = -2.0 * Nz# * VdotN# 
	
	; Add the normal force to the motion vector. 
	xvel#=(xvel# + NFx#)*bounce#
	yvel#=(yvel# + NFy#)*bounce#
	zvel#=(zvel# + NFz#)*bounce#
Next



Steven Noyce(Posted 2006) [#4]
Thanks!
Here is mindstorms code put into the "simple program" I was talking about.
nx#=Input("nx: ")
ny#=Input("ny: ")
nz#=Input("nz: ")

vx#=Input("vx: ")
vy#=Input("vy: ")
vz#=Input("vz: ")

; Compute the dot product of the ball's motion vector and the normal of the surface collided with. 
VdotN# = vx*Nx + vy*Ny + vz*Nz

; Calculate the normal force.
NFx# = -2.0 * Nx * VdotN
NFy# = -2.0 * Ny * VdotN
NFz# = -2.0 * Nz * VdotN

; Add the normal force to the motion vector.
vx#=(vx + NFx);*bounce#
vy#=(vy + NFy);*bounce#
vz#=(vz + NFz);*bounce#

Print vx+" , "+vy+" , "+vz

WaitKey()

It seems to work ok, but I am not sure if it works corectly all of the time, I will go test it out.


Matty(Posted 2006) [#5]
The bit where you have "-2.0 *" can be replaced with the following, for inelastic collisions:

"-(1.0+Elasticity#) *", where Elasticity is a floating point value between 0 and 1.0 with 1.0 being fully elastic collisions (rebound to same height) and 0.0 being fully inelastic collisions (no bounce).


Steven Noyce(Posted 2006) [#6]
Thanks! Good to know!


mindstorms(Posted 2006) [#7]
Just for clarity, my first post is my code but the second post was someone elses in the code archives. I don't remember where though...