# How can I make this code better?

Hello I feel like there’s a better way of doing this but I can’t think of anything and it’s very frustrating.
The code is casting a ray in 6 directions from the part’s middle to it’s surface, to cover the area inside of the part. Everything works but I don’t like how it looks.

``````local Vectors ={Vector3.new(Part.Size.X/2,0,0),Vector3.new(0,Part.Size.Y/2),Vector3.new(0,0,Part.Size.Z/2),Vector3.new(-Part.Size.X/2,0,0),Vector3.new(0,-Part.Size.Y/2),Vector3.new(0,0,-Part.Size.Z/2)}
local connection
connection = RunService.Heartbeat:Connect(function()
for i = 1,6 do
local raycast = workspace:Raycast(Part.Position,Vectors[i],raycastParams)

if raycast then -- if something is hit
local HitPart = raycast.Instance

--connection:Disconnect()
end
end

``````

I’m not an advanced programmer but code looks fine to me. Maybe try capitalizing some variables and it might make things look a bit better.

I’d probably make the Vectors variable on multiple lines, such as:

``````local Vectors = {
...
}
``````

Provides better readabilty. Usually it’s a good idea to store a value as a variable if it is used more than once, for example Part.Size is used 6 times. Also, the last 3 Vectors are just the inverted first 3. You might be able to shorten it with that.

I’d change the 6 to #Vectors.

Other than that, it seems fine to me. No major issue and I’m not sure any of my suggestions really are worth the time either.

• Wrap table that is too long
• use ipairs replace number,when modifying the quantity of tables in this way, you do not need to modify the code
``````local partSize = Part.Size
local directions ={
Vector3.new(partSize.X/2,0,0),
Vector3.new(0,partSize.Y/2),
Vector3.new(0,0,partSize.Z/2),
Vector3.new(-partSize.X/2,0,0),
Vector3.new(0,-partSize.Y/2),
Vector3.new(0,0,-partSize.Z/2)
}
local connection
connection = RunService.Heartbeat:Connect(function()
for _, direction in ipairs(directions) do
local raycast = workspace:Raycast(Part.Position,direction,raycastParams)
if raycast then -- if something is hit
local hitPart = raycast.Instance
--connection:Disconnect()
end
end
)
``````
1 Like

Are you sure raycasts is the best solution for this? Check out GetPartsInPart if that’s what you’re trying to do