hi everyone!
i was following a tutorial (from a book) about collision detection using maths…and what i basically did was read the code/explnation, understand it and then attempt to write it out myself without the aid of the book. All went well (ish…a few peeks and checks:P) but for one particular section i left out VAR…and the result was rather unexpected. here is the function which has the VAR question…(btw, this is Flash MX)
function detectCollision(b1,b2){
//The positions
var xl1 = b1.xpos;
var yl1 = b1.ypos;
var xl2 = b2.xpos;
var yl2 = b2.ypos;
//The speeds
var xmove1 = b1.xmove;
var ymove1 = b1.ymove;
var xmove2 = b2.xmove;
var ymove2 = b2.ymove;
//The Caculation...
var R = b1.radius + b2.radius;
var Xc = xl2*xl2-2*xl2*xl1+xl1*xl1;
var Xb = 2*(xl2*xmove2-xl2*xmove1-xl1*xmove2+xl1*xmove1);
var Xa = xmove2*xmove2-2*xmove2*xmove1+xmove1*xmove1;
var Yc = yl2*yl2-2*yl2*yl1+yl1*yl1;
var Yb = 2*(yl2*ymove2-yl2*ymove1-yl1*ymove2+yl1*ymove1);
var Ya = ymove2*ymove2-2*ymove2*ymove1+ymove1*ymove1;
var a = Xa + Ya;
var b = Xb + Yb;
var c = Xc + Yc - R*R;
var delta = Math.sqrt(b*b-4*a*c);
var t1 = (-b+delta)/(2*a);
var t2 = (-b-delta)/(2*a);
if(t1>0 && t1<=1){
var whatTime = t1;
var collide = true;
}
if(t2>0 && t2<=1){
if(whatTime == null || t2<t1){
var whatTime = t2;
var collide = true;
}
}
if(collide){
trace("bang bang bang...")
}
}
ok, near the bottom of it where we’re looking at t2, initially i just put:
whatTime = t2;
collide = true;
because i thought, well, we already used ‘var’ to define those 2 variables…but what happened was once the Circles(i know i said balls…but their circles) ‘hit’ it would continuously output “bang bang bang…” even after they didn’t hit.
and by simply adding ‘var’ infront of those two variables it worked perfect! outputted “bang bang bang…” first time it touched and last time it touched…
so i was just wondering what exactly does ‘var’ do? (btw, the only reason i put in var in the beginning was because i peeked)
oh, and just one other thing i remembered when i looked back at the code…
the line:if(whatTime == null || t2<t1)
i know means: If WhatTime does not have a value OR t2 less than t1 then do whatever…
but i still haven’t quite understood - despite several attempts - why it is there.
ill attach the fla file so it will make more sense. (oh, and i can’t spell:P)
thank you!
pyko
p.s im new to actionscript, but i do sort of have some prior programming knowledge though not alot…so explain even the most simplest and glaring things