Camera Movement Constraint

How would you recommend constraining the camera to the grid (in the completed project)?

Welcome to the community, @Stuart_Mansur

You could prevent the CameraController from moving beyond the grid. Something like this

    // This is in CameraMovement.cs
    private void HandleMovement()
    {
        var inputMoveDir = InputManager.Instance.GetCameraMoveVector();
        var moveVector = transform.forward * inputMoveDir.y + transform.right * inputMoveDir.x;
        transform.position = CalculateConstrainedPosition(moveVector);
    }

    private Vector3 CalculateConstrainedPosition(Vector3 moveVector)
    {
        // this should be cached
        var width = LevelGrid.Instance.GetWidth() - 1;
        var height = LevelGrid.Instance.GetHeight() - 1;
        var minConstraintVector = LevelGrid.Instance.GetWorldPosition(new GridPosition(0, 0));
        var maxConstraintVector = LevelGrid.Instance.GetWorldPosition(new GridPosition(width, height));

        // calculate the new position
        var newPosition = transform.position + moveVector * _moveSpeed * Time.deltaTime;
        // clamp the position to grid bounds
        newPosition.x = Mathf.Clamp(newPosition.x, minConstraintVector.x, maxConstraintVector.x);
        newPosition.z = Mathf.Clamp(newPosition.z, minConstraintVector.z, maxConstraintVector.z);
        return newPosition;
    }
1 Like

The camera is following the invisible camera Game Object, so if you want you can just add a limit when moving that object, get it’s position and ask the LevelGrid if the position is valid, if not then don’t move
Pretty simple and that way the target point will always be inside the grid.

3 Likes

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

Privacy & Terms