Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

Can someone explain the math in this script? I'm lost.

Asked by 4 years ago

taken from the wiki

local ray = Ray.new(tool.Handle.CFrame.p, (mouse.Hit.p - tool.Handle.CFrame.p).unit * 300)

why are we subtracting the handle's cframe?

beam.CFrame = CFrame.new(tool.Handle.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)

okay, now why are we subtracting distance, and why the hell is it divided by 2?

why can we not just make a ray from the handle to mouse.hit?

2 answers

Log in to vote
1
Answered by 4 years ago

Vector subtraction calculates a vector which points from the subtracting vector to the subtracted vector. Ray.new() takes the origin and the direction of the ray, and the ray is going to point from the handle to the mousehit, so that is why the vector is subtracted.

In the second case, multiplying by a CFrame represents displacement. Because the beam is being set to the handle's CFrame in CFrame.new(tool.Handle.CFrame.p, position), it would be centered on the handle. Halfway between the end and the origin is half the distance, so that is why it is multiplied by a displacement of half the distance.

Need clarification? Let me know.

0
Maybe elaborate just a bit, dumb it down for me please. BIuehawks 62 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

So for Ray.new(), the two arguments are the Start Position, and the Direction.

An easy way of calculating the Direction in this instance is to find the Unit, which is the Vector3 position 1 stud away from Vector3.new(0, 0, 0) in that direction. To find the unit, you can subtract the End Position from the Start Position to give you a single Vector that defines the difference between the two Vectors, then use the .Unit part of that Vector to give you the unit.

Picture a straight road, if you are 10km from the start of that road, and your destination is 20km from the start of that road, you can do EndPosition (20km) - StartPosition (10km) and it will give you the difference between you and that destination (10km). Your example is the same maths, just using a 3D position vectors instead.

For the second part, where it is positioning the beam along your Ray. When you set a part's CFrame, it will move the centre of that part to the CFrame you have given it. Sometimes, like in this example, that's not ideal as the beam's centre would be at your Tool's Handle part position which means half of it would stick out behind, and the other half would stick out infront. To offset this, *CFrame.new(0, 0, -distance/2) [Multiplying CFrames together like this adds the components] would offset your beam by half the distance of the beam, which means the start of the beam would align with the middle of your tool's handle, which is what you want.

Apologies for the poor explanation, it's a difficult one to get your head around without images.

Answer this question