so this is the code for my raycast
1 | local ray = Ray.new(char:FindFirstChildOfClass( "Tool" ).tool.barrel.Position,(pos).Unit * 5 ) --starts the ray |
2 | local hit = game.Workspace:FindPartOnRay(ray) |
3 | if hit then |
4 | print (hit, " yay!" ) |
5 | else |
6 | print (hit, " awww" ) |
7 | end |
it always prints nil awww even when i hit something and it is closer than 5 studs and at the thing im standing on too please help
fifkey i changed the raycast to this:
1 | local ray = Ray.new(char:FindFirstChildOfClass( "Tool" ).tool.barrel.Position,(pos-char:FindFirstChildOfClass( "Tool" ).tool.barrel.Position).Unit * 5 ) --starts the ray |
it didn't work is there anything else i did wrong?
So this script basically gets the position from the camera to the point in world space and then makes a new ray from your gun barrel to where ever the click location is at. I have explained a bit more with comments.
01 | local tool = script.Parent |
02 | local UserInputService = game:GetService( "UserInputService" ) |
03 | local player = game.Players.LocalPlayer |
04 | local Camera = workspace.CurrentCamera |
05 | local equipped = false |
06 | local character = player.Character:GetChildren() |
07 | local toolOrigin = character:FindFirstChildOfClass( "Tool" ).tool.barrel.Position |
08 | local RE = game.ReplicatedStorage:WaitForChild( "RemoteEvent1" ) |
09 |
10 | tool.Equipped:Connect( function () |
11 | equipped = true |
12 | end ) |
13 |
14 | tool.Unequipped:Connect( function () |
15 | equipped = false |
Server script:
01 | local RE = Instance.new( "RemoteEvent" ) |
02 | RE.Name = "RemoteEvent1" |
03 | RE.Parent = game.ReplicatedStorage |
04 |
05 | RE.OnServerEvent:Connect( function (player,toolOrigin,worldCF,character) |
06 | local ray = Ray.new(toolOrigin,(worldCF.Position-toolOrigin).Unit) |
07 | local ray 1 = Ray.new(ray.Origin,ray.Direction * 1000 ) |
08 | local part, hitPos, norm = workspace:FindPartOnRayWithIgnoreList(ray 1 ,character) |
09 | if part then |
10 | print (part, " yay!" ) |
11 | else |
12 | print (part, " awww" ) |
13 | end |
14 | end ) |
Make sure that the second value of Ray.new is a unit vector. A unit vector is a vector value with a magnitude of 1, used to indicate a direction. To make a unit out of two positions, you use (PositionB - PositionA).Unit
and multiply that value by a scalar (a number). If that's too complicated, you can also do CFrame.new(PositionA, PositionB).LookVector * Scalar
as well.