EDIT: Spoke to a friend and they suggested a better solution, which is to use nested tables of level data (which also lets me create parts on the fly) and predefined positions. Never figured out why I ran into the original issue, but it is no longer applicable!
Trying to create a function that moves the player as far forward as possible in one direction following a grid using raycasts, but certain patterns of movement cause the player to be offset from the grid.
My code moves the player to the position of the raycast result with an offset to keep them on the grid, and I’ve tried adjusting it, but moving in random directions just causes problems.
Here is what is supposed to happen:
And here is what ends up happening:
The brick surrounding the player is 5x5 and welded to the HumanoidRootPart. It is what the raycast sends from. I also use Collision Groups and Raycast Filtering to ensure that only the walls are hit. The whole level is 70x70, and every piece is also 5x5 (the walls are a union, but have no special function)
-- Movement Function
if (this.MovementEnabled) then
if (direction == SharedEnums.MovementDirection.Up) then
local result = WorkspaceService:Raycast(this.CurrentCharacter.colliderPart.Position, Vector3.new(70, 0, 0), MovementRaycastParams);
if (result) then
print(result.Position)
this.CurrentCharacter:PivotTo(CFrame.new((result.Position + Vector3.new(-1.25, 0, 0))));
end
elseif (direction == SharedEnums.MovementDirection.Left) then
local result = WorkspaceService:Raycast(this.CurrentCharacter.colliderPart.Position, Vector3.new(0, 0, -70), MovementRaycastParams);
if (result) then
print(result.Position)
this.CurrentCharacter:PivotTo(CFrame.new((result.Position + Vector3.new(0, 0, 1.25))));
end
elseif (direction == SharedEnums.MovementDirection.Down) then
local result = WorkspaceService:Raycast(this.CurrentCharacter.colliderPart.Position, Vector3.new(-70, 0, 0), MovementRaycastParams);
if (result) then
print(result.Position)
this.CurrentCharacter:PivotTo(CFrame.new((result.Position + Vector3.new(2.5, 0, 0))));
end
elseif (direction == SharedEnums.MovementDirection.Right) then
local result = WorkspaceService:Raycast(this.CurrentCharacter.colliderPart.Position, Vector3.new(0, 0, 70), MovementRaycastParams);
if (result) then
print(result.Position)
this.CurrentCharacter:PivotTo(CFrame.new((result.Position + Vector3.new(0, 0, -1.25))));
end
end
else
return false;
end
I’m for a loss at how these are getting so far from the grid, and any clues would be awesome.
I know it could also be optimized, but I’m just trying to get a prototype working for now.