admin管理员组

文章数量:1123419

I’m playing around with procedurally generated terrain and the new TileMapLayer in Godot 4. Very nice and easy to generate terrain.

I’d like to generate the terrain in the visible area of the Camera2D, regardless of current zoom.

My zoom function in Camera2D:

public void ZoomCamera(double delta)
{
    Vector2 zoom = Zoom;
    if (Input.IsActionJustPressed("camera_zoom_in"))
    {
        zoom.X = Mathf.Clamp(zoom.X * 1.1f, MinZoom, MaxZoom);
        zoom.Y = Mathf.Clamp(zoom.Y * 1.1f, MinZoom, MaxZoom);
    }

    if (Input.IsActionJustPressed("camera_zoom_out"))
    {
        zoom.X = Mathf.Clamp(zoom.X * 0.9f, MinZoom, MaxZoom);
        zoom.Y = Mathf.Clamp(zoom.Y * 0.9f, MinZoom, MaxZoom);
    }
    Zoom = Zoom.Slerp(zoom, (float)(ZoomSpeed * delta));
}

I can translate the current mouse position and use that to select any tile:

var clickedCell = LocalToMap(GetLocalMousePosition());
SetCell(clickedCell, 0, new Vector2I(6, 0), 0);

Now when I try and calculate the viewport bounds and convert to local, its not the same coordinates as the mouse position.

public void ReCalculateViewPortBounds()
{
    var viewport = GetViewport();
    var camera = viewport.GetCamera2D();

    var viewportSize = viewport.GetVisibleRect().Size;
    var cameraPosition = camera.GlobalPosition;

    var half_width = (viewportSize.X * Zoom.X) / 2f;
    var half_height = (viewportSize.Y * Zoom.Y) / 2f;

    // Define corners
    var top_left = cameraPosition + (new Vector2(-half_width, -half_height));
    var top_right = cameraPosition + (new Vector2(half_width, -half_height)); 
    var bottom_left = cameraPosition + (new Vector2(-half_width, half_height));
    var bottom_right = cameraPosition + (new Vector2(half_width, half_height));

    // Send event
    EventBus.Instance.Bus.Publish<CameraEvent>(new CameraEvent {
        BottomLeft = ToLocal(bottom_left),
        BottomRight = ToLocal(bottom_right),
        TopLeft = ToLocal(top_left),
        TopRight = ToLocal(top_right)
    });
}

Which produces:

Essentially, I’m trying to get the same coordinates as if I click the mouse in all four corners of the map at any given zoom level.

本文标签: cDetermine visible area of TileMapLayer in GodotStack Overflow