Vectors
Blitz3D Forums/Blitz3D Beginners Area/Vectors
| ||
I'm doing a 2d physics simulation and as such I need to use vectors a lot. However I'm new to programming so I don't know the best way to implement them. For instance I tried to make a function that you pass two vectors to and it return their sum as a vector. Function Add_Vectors.Tvector(v1.Tvector,v2.Tvector) u.Tvector = new Tvector u\x = v1\x + v2\x u\y = v2\y + v2\y return u End Function Now I realise that this is just passing the memory address of the new vector just created so every time this is called it creates a new Tvector. Is there a way to use nice functions like this properly? Also, is it bad programming practice to continually create/delete objects. This is what I intended to do for my collision sorting algorithm. |
| ||
http://blitzbasic.com/codearcs/codearcs.php?code=936 |
| ||
That library is almost identical to the one I made. The problem is that new vectors are being made constantly; there were about 2000 vector objects made in the first 3 seconds by my Euler algorithm: Function Approximate_Next_Quantities(b.Tbody) delta_t# = 1/Float(EULER_STEPS) t# = 0 left_a.Tvector = New Tvector right_a.Tvector = New Tvector average_a.Tvector = New Tvector v.Tvector = New Tvector r.Tvector = New Tvector ; set initial values v = b\v r = b\r temp_v.Tvector = New Tvector temp_r.Tvector = New Tvector For i = 0 To EULER_STEPS-1 left_a = Acceleration_Function(t, v, r) temp_v = Add_Vectors(v,Multiply_Scalar_Vector(delta_t,left_a)) temp_r = Add_Vectors(r,Multiply_Scalar_Vector(delta_t,v)) right_a = Acceleration_Function(t+delta_t, temp_v, temp_r) average_a = Multiply_Scalar_Vector(0.5,Add_Vectors(left_a,right_a)) v = Add_Vectors(v,Multiply_Scalar_Vector(delta_t,average_a)) r = Add_Vectors(r,Multiply_Scalar_Vector(delta_t,v)) t = t + delta_t Next b\next_v = v.Tvector b\next_r = r.Tvector ;Delete objects Delete left_a Delete right_a Delete average_a Delete temp_v Delete temp_r End Function Function Acceleration_Function.Tvector(t#,v.Tvector,r.Tvector) u.Tvector = New Tvector u\x = 0 u\y = 0.1 Return u End Function Is there a way I can do this properly? |
| ||
You could just define as many of those temporary Tvectors as needed as globals, outside the function.Type Tvector Field x# Field y# Field z# End Type Global u.Tvector = New Tvector Function Acc.Tvector () u\x = 0 u\y = 0.1 Return u End Function test.Tvector = Acc () Print test\x Print test\y MouseWait |
| ||
Thanks! That's exactly what I needed. Now I just send one of the global temporary vectors to the function as an argument. This makes very complicated vector equations possible by using different temporary vectors in the same equation. Thanks again, Sam |