Author Topic: How to reflect/bounce a vector off a normal?  (Read 501 times)

I'm trying to get a vector to "bounce" using an incoming vector and a normal vector. In this case, I am using the muzzleVector of an image for %vector and a normal retrieved from an earlier raycast for %normal.

Code: [Select]
function getBounceVector(%vector, %normal)
{
%v = %vector;
%n = %normal;

%reflectVec = vectorAdd(vectorCross(vectorCross(vectorDot(%v, %n), %n), -2), %v);
return %reflectVec;
}

I'm not very good at vector math. This seems to work, but for some reason, will only reflect on surfaces facing up, down, north and south. For west and east facing surfaces, %reflectVec ends up being equal to %vector, as if it was just penetrating straight through the surface.
« Last Edit: June 03, 2017, 11:12:51 AM by Rally »

It should be something like

%n = vectorNormalize(%n); // remove if your normal already has length 1
return vectorSub(%v, vectorScale(%n, 2 * vectorDot(%v, %n)));


Not sure if I got it right, it might be pointing in the wrong direction

Worked perfectly, thanks mate

I know I sent you a late PM response but I'll mind as well post the source of the actual Projectile::Bounce function

Code: [Select]
registerOutputEvent("Projectile", "Redirect", "vector 200" TAB "bool");
function Projectile::Bounce(%obj, %factor, %client)
{
%vel = %obj.getLastImpactVelocity();
%norm = %obj.getLastImpactNormal();
%bounceVel = VectorSub(%vel, VectorScale(%norm, VectorDot(%vel, %norm) * 2));
%bounceVel = VectorScale(%bounceVel, %factor);
if (VectorLen(%bounceVel) > 200)
%bounceVel = VectorScale(VectorNormalize(%bounceVel), 200);

%p = new Projectile()
{
dataBlock = %obj.getDataBlock();
initialPosition = %obj.getLastImpactPosition();
initialVelocity = %bounceVel;
sourceObject = 0;
sourceSlot = %obj.sourceSlot;
client = %obj.client;
};

if (%p)
{
MissionCleanup.add(%p);
%p.setScale(%obj.getScale());
%p.spawnBrick = %obj.spawnBrick;
}

%obj.delete();
}