I want to have certain circular objects bounce against all four sides of the screen. After searching a lot on the internet, I found the following formula:
Vout = Vin - ((1+e) *dot(Vnormal, Vin) * Vnormal)
However, I am having difficulties to implement this formula in my current engine, for the following reasons:
- My object's next position is determined using a Velocity and a Direction(in radians) property. This means that I need to convert it to and from vectors each time I use this formula.
- Because screen-coordinates move from the top left (and not the bottom left as in math), I calculate the next position of the objects using the following:
var newx = -Math.sin(this.rotation)*this.speed;
var newy = Math.cos(this.rotation)*this.speed;
Currently, I am doing the following:
vinx = -Math.sin(this.rotation)*this.speed; viny = Math.cos(this.rotation)*this.speed; var vnormalx = 0; var vnormaly = 1;//Should bounce against bottom of the screen. var e = 1;//Restitution. Is 1, thus object should get full energy back. var voutx = vinx - (1+e) * ((vnormalx*vinx)+(vnormaly*viny)) *vnormalx; var vouty = viny - (1+e) * ((vnormalx*vinx)+(vnormaly*viny)) *vnormaly; var newspeed = Math.sqrt(Math.pow(voutx, 2)+Math.pow(vouty, 2)); //pythagoras to get magnitude(the length) of the vector. var newrotation = Math.atan(voutx/vouty); //angle of vector this.rotation = newrotation; this.speed = newspeed;
So, this is not working. I have no clue why. I tried changing the normal vector to (0, -1) and even (1, 0) and (-1, 0), but no cigar. I think this might have to do with the way I have rotated the x and y perspective, but I have no idea how to change this, or if it indeed is the cause of the problem or not.