Weapon Raycast help

I am making a first person shooter which is pvp. For my weapons, i had an older system which instantiated a part and gave it a velocity. This system however, was laggy and had hit detection problems. I then heard of another widely used method, which is firing the clients to locally make a part and give it a velocity (which would be for show) and then the server would iterate over the bullet’s path, making rays every few increments and checking for parts on that ray.

I have been trying to implement this, but i am not having much luck. Im pretty lost when it comes to understanding this. The code seems to give the projectile drop, but for some reason does not produce the correct direction

I have this code segment right here:

Functions (@tyridge77 gave me these, i did not write them):

local function CalculateStartVelocity(pos, goal, power, accuracy)
	local maxAngle = math.rad(125)*math.clamp(1 - accuracy, 0, 1)
    return (CFrame.new(pos, goal)*CFrame.Angles(0, 0, math.random(0, 2*math.pi))*CFrame.Angles(math.acos(math.random(math.cos(maxAngle), 1)), 0, 0)).LookVector*power
end


local function CalculateProjectilePosition(startpos, startvelocity, timeSince,gravity)
	return startpos + startvelocity * timeSince + 0.5 * gravity * timeSince ^ 2;
end

Implementation:

        local CurrentPosition = pos.p
		local LastPosition = CurrentPosition
		local StartVelocity = CalculateStartVelocity(pos.p, pos.LookVector*2, speed, 10)
		
		print(StartVelocity)
		
		for i = 1, 50 do wait(0.01)
			CurrentPosition = CalculateProjectilePosition(LastPosition, StartVelocity, (0.1 * i), Vector3.new(0, workspace.Gravity * bolt:GetMass() * bolt.Drop.Value, 0))
			
			local ray = Ray.new(LastPosition,CurrentPosition-LastPosition);
			
			
			local beam = Instance.new("Part", workspace) -- so i can see the path
			beam.CanCollide = false
			beam.Anchored = true
			beam.Material = "Neon"
			
			
			beam.Position = LastPosition
			
			LastPosition = CurrentPosition
		end
1 Like

I’ve found the pos (the CFrame value passed from the client to the server, it is the position of a part called ‘ray’, which is a part positioned at the end of the player’s gun) value works fine (appears correctly when i instantiate a part on that location) but pos.LookVector seems to only end up at a single place.

Edit: (oof, my bad. I forgot that CFrame.LookVector is an incremental value, and must have its CFrame applied to it to have the desired result)

goal in CalculateStartVelocity is supposed to be a position, not a direction

1 Like

Did i say CFrame? i meant position, sorry

In your implementation example you pass in

 pos.LookVector*2

As goal in CalculateStartVelocity. That’s a direction. Goal is supposed to be a position

1 Like

i figured goal would be a value further down the projectile’s path, so i used the projectile’s LookVector to find that. at any rate, i have it working if you would like to see:

Thank you for your help @tyridge77