Skip to content
This repository has been archived by the owner on Jun 7, 2024. It is now read-only.

Commit

Permalink
Initial work to make platforms re-generate
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanlangston committed Nov 28, 2023
1 parent d8dd1fd commit 3a05d45
Showing 1 changed file with 46 additions and 11 deletions.
57 changes: 46 additions & 11 deletions src/Models/World.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const PlayerModel = @import("../Models/Player.zig").Player;
const PlatformModel = @import("../Models/Platform.zig").Platform;
const Shared = @import("../Helpers.zig").Shared;
const Logger = @import("../Logger.zig").Logger;
const RndGen = std.rand.DefaultPrng;

pub const World = struct {
pub var Player: PlayerModel = undefined;
Expand All @@ -13,6 +14,8 @@ pub const World = struct {
pub fn Init() !void {
Deinit();

rnd = RndGen.init(@intCast(std.time.nanoTimestamp()));

const screenWidth: f32 = @floatFromInt(raylib.getScreenWidth());
const screenHeight: f32 = @floatFromInt(raylib.getScreenHeight());
const PlayerSize = PlayerModel.GetSize(raylib.Rectangle.init(0, 0, screenHeight, screenWidth));
Expand Down Expand Up @@ -94,18 +97,50 @@ pub const World = struct {
return null;
}

var rnd: RndGen = undefined;
pub fn UpdatePlatforms(yOffset: f32, current_screen: raylib.Rectangle) std.ArrayList(PlatformModel) {
for (Platforms.items, 0..) |platform, index| {
Platforms.replaceRange(
index,
1,
&[1]PlatformModel{
platform.UpdatePosition(yOffset, current_screen),
},
) catch {
Logger.Info("Failed to update platform!");
};
// Iterate through the platforms in reverse to safely remove elements while iterating
var index: usize = Platforms.items.len;
while (index > 0) {
index -= 1;

const platform = Platforms.items[index];
const updatedPlatform = platform.UpdatePosition(yOffset, current_screen);

if (updatedPlatform.Position.y + (updatedPlatform.Size.height * 2) > current_screen.height) {
// Remove platform that is no longer on screen
_ = Platforms.swapRemove(index);

// Add platform
const newPlatform = PlatformModel{
.Position = raylib.Rectangle.init(
rnd.random().float(f32) * current_screen.width,
-(updatedPlatform.Size.height * 2),
current_screen.width,
current_screen.height,
),
.Size = .{
.height = 2,
.width = @floatFromInt(rnd.random().intRangeAtMost(i32, 10, 50)),
},
};
Platforms.append(newPlatform) catch {
Logger.Error("Failed to update platform!");
};
} else {
// Replace Platform with updated version of the same platform
Platforms.replaceRange(
index,
1,
&[1]PlatformModel{
updatedPlatform,
},
) catch {
Logger.Error("Failed to update platform!");
};
}
}

return Platforms;
}

Expand All @@ -122,4 +157,4 @@ pub const World = struct {
);
return current_screen;
}
};
};

0 comments on commit 3a05d45

Please sign in to comment.