So I have this code here for a custom raycaster engine of mine that allows me to map textures based on coordinates and distances from the raycasting. I have a variable which I have used to define the 2D on-screen space of where a portion of texture would show (ImagePosX
)
My main issue here is that I am repeating a lot of very similar code and I would like to know if there was a way to make this code waaaay smaller than it should be. Cause to be honest, this looks a lot more complicated than it actually is and probably doesn’t even need to be this complicated to begin with.
How can I make this smaller and use way less repetition for checking all faces manually?
local Face = NormalToFace(ViewRay.Normal, HitPart) -- Get Enum face from normal vector
-- Make sure the textures dont reverse
-- There is probably a better way of doing this, but this is the only solution I could think of.
if HitPart.Orientation.Y >= -135 and HitPart.Orientation.Y <= -45 then -- Right
if Face == Enum.NormalId.Right or Face == Enum.NormalId.Left then
ImagePosX = (HitPart.Position.X) - (ViewRay.Position.X)
if Face == Enum.NormalId.Left then
ImagePosX = -ImagePosX
end
else
ImagePosX = (HitPart.Position.Z) - (ViewRay.Position.Z)
if Face == Enum.NormalId.Front then
ImagePosX = -ImagePosX
end
end
end
if HitPart.Orientation.Y >= -45 and HitPart.Orientation.Y <= 45 then -- Front
if Face == Enum.NormalId.Front or Face == Enum.NormalId.Back then
ImagePosX = (HitPart.Position.X) - (ViewRay.Position.X)
if Face == Enum.NormalId.Front then
ImagePosX = -ImagePosX
end
else
ImagePosX = (HitPart.Position.Z) - (ViewRay.Position.Z)
if Face == Enum.NormalId.Right then
ImagePosX = -ImagePosX
end
end
end
if HitPart.Orientation.Y >= 45 and HitPart.Orientation.Y <= 135 then -- Left
if Face == Enum.NormalId.Right or Face == Enum.NormalId.Left then
ImagePosX = (ViewRay.Position.X) - (HitPart.Position.X)
if Face == Enum.NormalId.Left then
ImagePosX = -ImagePosX
end
else
ImagePosX = (HitPart.Position.Z) - (ViewRay.Position.Z)
if Face == Enum.NormalId.Back then
ImagePosX = -ImagePosX
end
end
end
if (HitPart.Orientation.Y >= 135 and HitPart.Orientation.Y >= -135) or (HitPart.Orientation.Y <= -135) then -- Back
if Face == Enum.NormalId.Front or Face == Enum.NormalId.Back then
ImagePosX = (HitPart.Position.X) - (ViewRay.Position.X)
if Face == Enum.NormalId.Back then
ImagePosX = -ImagePosX
end
else
ImagePosX = (HitPart.Position.Z) - (ViewRay.Position.Z)
if Face == Enum.NormalId.Left then
ImagePosX = -ImagePosX
end
end
end