Ray casts slightly behind player when moving

Hello,
I am trying to make a basic raycast from in front of the player’s HRP to 5 studs ahead, and this works fine standing still. But when the player is moving, the raycast seems to lag behind and it doesn’t seem to really begin the cast in front of the HRP like I want it too.
example
Here is the script (serverscript):

sendAttack.OnServerEvent:Connect(function(player,attackCooldown)
	if attackDebounce == false then attackDebounce = true
		coroutine.wrap(function()
			task.wait(attackTime)
			castRay()
		end)()
		task.wait(attackCooldown)
		attackDebounce = false
	end
end)

function castRay()
	local origin = rootpart.Position
	local direction = rootpart.CFrame.lookVector * 5
	local rayParams = RaycastParams.new()
	local rayResult = workspace:Raycast(origin,direction,rayParams)
	
	if rayResult then
		if rayResult.Instance.Parent:FindFirstChild("Humanoid") then
			rayResult.Instance.Parent.Humanoid:TakeDamage(damage)
			print("Did "..damage.." to "..rayResult.Instance.Parent.Name)
		end
	end
end

Is there a good way to correct this behavior? And while I’m asking questions, is there a good way to fire the same ray three times, except it fires from the HRP slightly up or down (preferably a way to control it from where the function is fired, which is the attack function)?
example2
Any help is appreciated!

maybe you could make the script check when a player is walking, and use an if statement to tell the raycast to move 5 studs up EDIT: you can use Humanoid:GetState() to check if the humanoid is walking

I tried doing something along those lines but I’m also not entirely sure how to:
A) put the ray’s starting position in front of its origin to begin with, including lookvectors, and
B) the player’s speed is also a contributing factor since the higher the speed of the player is, the more behind the ray will be

for A, i believe you can add the look vector to the origin

local origin = rootpart.Position + (rootpart.CFrame.LookVector * 5)

and for B WalkSpeed is a property you can check (its in humanoid if i remember properly), then you can customise the ray based on the walk speed with if statements.

1 Like

Was thinking about walkspeed, but I guess I’ll try it out. Thanks for the help!

1 Like

Note that the server and client are not always synchronous. There is an apparent lag from server to pick up your current position. Such as when you start walking forward, your character immediately responds on your client. The server however does not do this instantaneously and lags behind based on the latency response.

Extrapolation is possible, these predictions would rebalancing hitting a miss more frequent than missing a hit.

1 Like