Bug in my simple raycasting in 6 directions code

Argh … this I cannot see my mistake. What i am doing is simply sending a single raycast from the middle of a part in all six directions (in a straight line) to the edge of the part, thats at least how its supposed to work. If the platform is square etc 20,20,20 then it works fine, but if its not etc … 40,20,20 then the problem is the lenght of the ray (direction * size). For some reason that i cant grasp it will send a ray of ((direction * size / 2) in the wrong direction. so that if its the z direction of the part that is 40,20,20 then it will send a ray with the length of the x direction divided by two, i.e ~ 20 when it should be 10, i.e. the ray goes 10 studs outside the part…

local function isPlatformHit()
		local platform = Model.Penta:FindFirstChild("Platform")
		local size 

		for i, direction in ipairs({
			Vector3.new(1, 0, 0), 
			Vector3.new(-1, 0, 0), 
			Vector3.new(0, 1, 0), 
			Vector3.new(0, -1, 0), 
			Vector3.new(0, 0, 1), 
			Vector3.new(0, 0, -1)}) do

			if i <= 2 then
				size = platform.size.X
			elseif i == 3 or i == 4 then
				size = platform.size.Y
			elseif i == 5 or i == 6 then
				size = platform.size.Z
			end
			local rayOrigin = platform.Position
			local raycastResult = workspace:Raycast(rayOrigin, direction * size / 2, raycastParams)
			DEBUG_visualizeRay(rayOrigin, raycastResult)

			if raycastResult then
				return true
			end
		end
		return false
	end

While I’m not 100% sure whether or not I understand the issue, I am suspecting your part may not be oriented at 0, 0, 0? If so, that is the issue. While the respective axes’ sizes and the direction are correct, each axis will be mixed up because of the orientation of the part not being 0, 0,0 .

You should be able to omit the index check (remove the if i <= 2, elseif 3 or 4, elseif 5 or 6…). Then from there, there are a couple ways to get the ideal result, but the simplest would probably be something along these lines:

direction = platform.CFrame:VectorToWorldSpace(direction * size / 2)

local rayOrigin = platform.Position

local raycastResult = workspace:Raycast(rayOrigin, direction)

Doing this you translate each direction to be relative to your platform’s CFrame which will allow the directions to be correct regardless of your platform’s orientation.

image

2 Likes

Your correct regarding the orientation issue, and this fixes this.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.