add paddles that can move

This commit is contained in:
Schrottkatze 2024-02-23 10:11:52 +01:00
parent a1346780ab
commit 62571655ae
Signed by: schrottkatze
SSH key fingerprint: SHA256:hXb3t1vINBFCiDCmhRABHX5ocdbLiKyCdKI4HK2Rbbc
5 changed files with 194 additions and 20 deletions

View file

@ -5,7 +5,7 @@ pub struct Position {
}
impl Position {
pub fn new(x: u32, y: u32) -> Self {
pub const fn new(x: u32, y: u32) -> Self {
Self { x, y }
}
}

View file

@ -38,4 +38,32 @@ pub trait MovingObject: Object {
ctx.rect(prev_x, prev_y, width, height, BG);
self.display(ctx);
}
fn move_constrained(
&mut self,
x: i32,
y: i32,
constraint_start: Position,
constraint_end: Position,
) {
let Position { x: cur_x, y: cur_y } = self.position();
let Size { width, height } = self.size();
let new_x = if cur_x.saturating_add_signed(x) <= constraint_start.x {
constraint_start.x
} else if (cur_x + width.saturating_add_signed(y)) > constraint_end.x {
constraint_end.x - width
} else {
cur_x.saturating_add_signed(x)
};
let new_y = if cur_y.saturating_add_signed(y) < constraint_start.y {
constraint_start.y
} else if (cur_y + height.saturating_add_signed(y)) >= constraint_end.y {
constraint_end.y - height
} else {
cur_y.saturating_add_signed(y)
};
self.update_pos(new_x, new_y)
}
}

View file

@ -10,7 +10,7 @@ pub struct Rect {
}
impl Rect {
pub fn new(x: u32, y: u32, height: u32, width: u32) -> Self {
pub fn new(x: u32, y: u32, width: u32, height: u32) -> Self {
Self {
pos: Position::new(x, y),
size: Size::new(width, height),
@ -42,10 +42,10 @@ pub struct MovingRect {
}
impl MovingRect {
pub fn new(x: u32, y: u32, height: u32, width: u32) -> Self {
pub fn new(x: u32, y: u32, width: u32, height: u32) -> Self {
Self {
prev_pos: Position::new(x, y),
current: Rect::new(x, y, height, width),
current: Rect::new(x, y, width, height),
}
}