Raycasting help

I am currently working on a combat lock on for my upcoming game. The lock on system works great however you are able to lock on to enemies through walls. To prevent this, I’m trying to learn raycasting to see if there is any structures in the way. Here’s what I have right now:

--Looping through all parts inside region
		for _, part in pairs(partsInRegion) do
			local humanoid = part.Parent:FindFirstChild("Zombie")
			if humanoid and enemy == nil then
				--Making sure there isn't a wall in the way
				local wallRay = Ray.new(character.HumanoidRootPart.Position, Vector3.new(20,20,20))
				local hit, position, normal, material = workspace:FindPartOnRayWithIgnoreList(wallRay, {part})
				if hit then
					if hit.Parent:FindFirstChild("Zombie") or hit:FindFirstChild("Zombie") then
						local gui = game:GetService("ReplicatedStorage").CameraFolder.EnemyLockOn:Clone()
						gui.Parent = humanoid.Parent.Torso
						enemy = humanoid.Parent

Basically it goes through parts in the region and if there’s any it sees if it’s linked to the enemy. This code is very weird at the moment. What I mean by that is the fact it sometimes doesn’t lock on to the enemies. If anyone can inform me more about Raycasting, that’d be great. Thank you!

The second argument of ray.new is the direction, or the vector representing the direction that, when added onto the origin, would be the end point of the ray, or the target of the ray you could say

Based on this definition, you could say that:

target = origin + direction
And therefore
direction = target - origin

Because the direction is whats added onto the origin to get to some point, target

So I think what you would want to put in the second half of the ray.new is:
instead of Vector3.new(20,20,20)


It seems to work a little better. However it still sometimes does not lock onto the enemy. Maybe it’s something to do with the region. I’ll look into it.

EDIT: It was a mistake with the region3 part of the script. However I did what PapaBreadd said and it worked better. Thanks.

1 Like