Struct Vec2

Source
#[repr(C)]
pub struct Vec2 { pub x: f32, pub y: f32, }
Expand description

A 2-dimensional vector.

Fields§

§x: f32§y: f32

Implementations§

Source§

impl Vec2

Source

pub const ZERO: Vec2

All zeroes.

Source

pub const ONE: Vec2

All ones.

Source

pub const NEG_ONE: Vec2

All negative ones.

Source

pub const MIN: Vec2

All f32::MIN.

Source

pub const MAX: Vec2

All f32::MAX.

Source

pub const NAN: Vec2

All f32::NAN.

Source

pub const INFINITY: Vec2

All f32::INFINITY.

Source

pub const NEG_INFINITY: Vec2

All f32::NEG_INFINITY.

Source

pub const X: Vec2

A unit vector pointing along the positive X axis.

Source

pub const Y: Vec2

A unit vector pointing along the positive Y axis.

Source

pub const NEG_X: Vec2

A unit vector pointing along the negative X axis.

Source

pub const NEG_Y: Vec2

A unit vector pointing along the negative Y axis.

Source

pub const AXES: [Vec2; 2]

The unit axes.

Source

pub const fn new(x: f32, y: f32) -> Vec2

Creates a new vector.

Examples found in repository?
examples/asteroids.rs (line 29)
28fn wrap_around(v: &Vec2) -> Vec2 {
29    let mut vr = Vec2::new(v.x, v.y);
30    if vr.x > screen_width() {
31        vr.x = 0.;
32    }
33    if vr.x < 0. {
34        vr.x = screen_width()
35    }
36    if vr.y > screen_height() {
37        vr.y = 0.;
38    }
39    if vr.y < 0. {
40        vr.y = screen_height()
41    }
42    vr
43}
44
45#[macroquad::main("Asteroids")]
46async fn main() {
47    let mut ship = Ship {
48        pos: Vec2::new(screen_width() / 2., screen_height() / 2.),
49        rot: 0.,
50        vel: Vec2::new(0., 0.),
51    };
52
53    let mut bullets = Vec::new();
54    let mut last_shot = get_time();
55    let mut asteroids = Vec::new();
56    let mut gameover = false;
57
58    let mut screen_center;
59
60    loop {
61        if gameover {
62            clear_background(LIGHTGRAY);
63            let mut text = "You Win!. Press [enter] to play again.";
64            let font_size = 30.;
65
66            if asteroids.len() > 0 {
67                text = "Game Over. Press [enter] to play again.";
68            }
69            let text_size = measure_text(text, None, font_size as _, 1.0);
70            draw_text(
71                text,
72                screen_width() / 2. - text_size.width / 2.,
73                screen_height() / 2. - text_size.height / 2.,
74                font_size,
75                DARKGRAY,
76            );
77            if is_key_down(KeyCode::Enter) {
78                ship = Ship {
79                    pos: Vec2::new(screen_width() / 2., screen_height() / 2.),
80                    rot: 0.,
81                    vel: Vec2::new(0., 0.),
82                };
83                bullets = Vec::new();
84                asteroids = Vec::new();
85                gameover = false;
86                screen_center = Vec2::new(screen_width() / 2., screen_height() / 2.);
87                for _ in 0..10 {
88                    asteroids.push(Asteroid {
89                        pos: screen_center
90                            + Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.))
91                                .normalize()
92                                * screen_width().min(screen_height())
93                                / 2.,
94                        vel: Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.)),
95                        rot: 0.,
96                        rot_speed: rand::gen_range(-2., 2.),
97                        size: screen_width().min(screen_height()) / 10.,
98                        sides: rand::gen_range(3, 8),
99                        collided: false,
100                    })
101                }
102            }
103            next_frame().await;
104            continue;
105        }
106        let frame_t = get_time();
107        let rotation = ship.rot.to_radians();
108
109        let mut acc = -ship.vel / 100.; // Friction
110
111        // Forward
112        if is_key_down(KeyCode::Up) {
113            acc = Vec2::new(rotation.sin(), -rotation.cos()) / 3.;
114        }
115
116        // Shot
117        if is_key_down(KeyCode::Space) && frame_t - last_shot > 0.5 {
118            let rot_vec = Vec2::new(rotation.sin(), -rotation.cos());
119            bullets.push(Bullet {
120                pos: ship.pos + rot_vec * SHIP_HEIGHT / 2.,
121                vel: rot_vec * 7.,
122                shot_at: frame_t,
123                collided: false,
124            });
125            last_shot = frame_t;
126        }
127
128        // Steer
129        if is_key_down(KeyCode::Right) {
130            ship.rot += 5.;
131        } else if is_key_down(KeyCode::Left) {
132            ship.rot -= 5.;
133        }
134
135        // Euler integration
136        ship.vel += acc;
137        if ship.vel.length() > 5. {
138            ship.vel = ship.vel.normalize() * 5.;
139        }
140        ship.pos += ship.vel;
141        ship.pos = wrap_around(&ship.pos);
142
143        // Move each bullet
144        for bullet in bullets.iter_mut() {
145            bullet.pos += bullet.vel;
146        }
147
148        // Move each asteroid
149        for asteroid in asteroids.iter_mut() {
150            asteroid.pos += asteroid.vel;
151            asteroid.pos = wrap_around(&asteroid.pos);
152            asteroid.rot += asteroid.rot_speed;
153        }
154
155        // Bullet lifetime
156        bullets.retain(|bullet| bullet.shot_at + 1.5 > frame_t);
157
158        let mut new_asteroids = Vec::new();
159        for asteroid in asteroids.iter_mut() {
160            // Asteroid/ship collision
161            if (asteroid.pos - ship.pos).length() < asteroid.size + SHIP_HEIGHT / 3. {
162                gameover = true;
163                break;
164            }
165
166            // Asteroid/bullet collision
167            for bullet in bullets.iter_mut() {
168                if (asteroid.pos - bullet.pos).length() < asteroid.size {
169                    asteroid.collided = true;
170                    bullet.collided = true;
171
172                    // Break the asteroid
173                    if asteroid.sides > 3 {
174                        new_asteroids.push(Asteroid {
175                            pos: asteroid.pos,
176                            vel: Vec2::new(bullet.vel.y, -bullet.vel.x).normalize()
177                                * rand::gen_range(1., 3.),
178                            rot: rand::gen_range(0., 360.),
179                            rot_speed: rand::gen_range(-2., 2.),
180                            size: asteroid.size * 0.8,
181                            sides: asteroid.sides - 1,
182                            collided: false,
183                        });
184                        new_asteroids.push(Asteroid {
185                            pos: asteroid.pos,
186                            vel: Vec2::new(-bullet.vel.y, bullet.vel.x).normalize()
187                                * rand::gen_range(1., 3.),
188                            rot: rand::gen_range(0., 360.),
189                            rot_speed: rand::gen_range(-2., 2.),
190                            size: asteroid.size * 0.8,
191                            sides: asteroid.sides - 1,
192                            collided: false,
193                        })
194                    }
195                    break;
196                }
197            }
198        }
199
200        // Remove the collided objects
201        bullets.retain(|bullet| bullet.shot_at + 1.5 > frame_t && !bullet.collided);
202        asteroids.retain(|asteroid| !asteroid.collided);
203        asteroids.append(&mut new_asteroids);
204
205        // You win?
206        if asteroids.len() == 0 {
207            gameover = true;
208        }
209
210        if gameover {
211            continue;
212        }
213
214        clear_background(LIGHTGRAY);
215
216        for bullet in bullets.iter() {
217            draw_circle(bullet.pos.x, bullet.pos.y, 2., BLACK);
218        }
219
220        for asteroid in asteroids.iter() {
221            draw_poly_lines(
222                asteroid.pos.x,
223                asteroid.pos.y,
224                asteroid.sides,
225                asteroid.size,
226                asteroid.rot,
227                2.,
228                BLACK,
229            )
230        }
231
232        let v1 = Vec2::new(
233            ship.pos.x + rotation.sin() * SHIP_HEIGHT / 2.,
234            ship.pos.y - rotation.cos() * SHIP_HEIGHT / 2.,
235        );
236        let v2 = Vec2::new(
237            ship.pos.x - rotation.cos() * SHIP_BASE / 2. - rotation.sin() * SHIP_HEIGHT / 2.,
238            ship.pos.y - rotation.sin() * SHIP_BASE / 2. + rotation.cos() * SHIP_HEIGHT / 2.,
239        );
240        let v3 = Vec2::new(
241            ship.pos.x + rotation.cos() * SHIP_BASE / 2. - rotation.sin() * SHIP_HEIGHT / 2.,
242            ship.pos.y + rotation.sin() * SHIP_BASE / 2. + rotation.cos() * SHIP_HEIGHT / 2.,
243        );
244        draw_triangle_lines(v1, v2, v3, 2., BLACK);
245
246        next_frame().await
247    }
248}
More examples
Hide additional examples
examples/events.rs (line 9)
6async fn main() {
7    loop {
8        clear_background(WHITE);
9        root_ui().window(hash!(), Vec2::new(20., 20.), Vec2::new(450., 200.), |ui| {
10            let (mouse_x, mouse_y) = mouse_position();
11            ui.label(None, &format!("Mouse position: {mouse_x} {mouse_y}"));
12
13            let (mouse_wheel_x, mouse_wheel_y) = mouse_wheel();
14            ui.label(None, &format!("Mouse wheel x: {mouse_wheel_x}"));
15            ui.label(None, &format!("Mouse wheel y: {mouse_wheel_y}"));
16
17            widgets::Group::new(hash!(), Vec2::new(200., 90.))
18                .position(Vec2::new(240., 0.))
19                .ui(ui, |ui| {
20                    ui.label(None, "Pressed kbd keys");
21
22                    if let Some(key) = get_last_key_pressed() {
23                        ui.label(None, &format!("{key:?}"))
24                    }
25                });
26
27            widgets::Group::new(hash!(), Vec2::new(200., 90.))
28                .position(Vec2::new(240., 92.))
29                .ui(ui, |ui| {
30                    ui.label(None, "Pressed mouse keys");
31
32                    if is_mouse_button_down(MouseButton::Left) {
33                        ui.label(None, "Left");
34                    }
35                    if is_mouse_button_down(MouseButton::Right) {
36                        ui.label(None, "Right");
37                    }
38                    if is_mouse_button_down(MouseButton::Middle) {
39                        ui.label(None, "Middle");
40                    }
41                });
42        });
43        next_frame().await;
44    }
45}
examples/rustaceanmark.rs (lines 22-25)
10async fn main() {
11    let mut rustaceanes: Vec<Rustaceane> = Vec::new();
12    let rustacean_tex = load_texture("examples/rustacean_happy.png").await.unwrap();
13    rustacean_tex.set_filter(FilterMode::Nearest);
14
15    loop {
16        clear_background(Color::default());
17
18        if macroquad::input::is_mouse_button_down(MouseButton::Left) {
19            for _i in 0..100 {
20                rustaceanes.push(Rustaceane {
21                    pos: Vec2::from(macroquad::input::mouse_position()),
22                    speed: Vec2::new(
23                        rand::gen_range(-250., 250.) / 60.,
24                        rand::gen_range(-250., 250.) / 60.,
25                    ),
26                    color: Color::from_rgba(
27                        rand::gen_range(50, 240),
28                        rand::gen_range(80, 240),
29                        rand::gen_range(100, 240),
30                        255,
31                    ),
32                })
33            }
34        }
35
36        for rustaceane in &mut rustaceanes {
37            rustaceane.pos += rustaceane.speed;
38
39            if ((rustaceane.pos.x + rustacean_tex.width() / 2.) > screen_width())
40                || ((rustaceane.pos.x + rustacean_tex.width() / 2.) < 0.)
41            {
42                rustaceane.speed.x *= -1.;
43            }
44            if ((rustaceane.pos.y + rustacean_tex.height() / 2.) > screen_height())
45                || ((rustaceane.pos.y + rustacean_tex.height() / 2.) < 0.)
46            {
47                rustaceane.speed.y *= -1.;
48            }
49
50            draw_texture(
51                &rustacean_tex,
52                rustaceane.pos.x,
53                rustaceane.pos.y,
54                rustaceane.color,
55            );
56        }
57
58        draw_fps();
59        draw_text(
60            format!("Rustaceanes: {}", rustaceanes.len()).as_str(),
61            0.,
62            32.,
63            32.,
64            WHITE,
65        );
66
67        next_frame().await
68    }
69}
examples/ui.rs (line 57)
52    fn slots(&mut self, ui: &mut Ui) {
53        let item_dragging = &mut self.item_dragging;
54
55        let fit_command = &mut self.fit_command;
56        for (label, slot) in self.slots.iter_mut() {
57            Group::new(hash!("grp", slot.id, &label), Vec2::new(210., 55.)).ui(ui, |ui| {
58                let drag = Group::new(slot.id, Vec2::new(50., 50.))
59                    // slot without item is not draggable
60                    .draggable(slot.item.is_some())
61                    // but could be a target of drag
62                    .hoverable(*item_dragging)
63                    // and is highlighted with other color when some item is dragging
64                    .highlight(*item_dragging)
65                    .ui(ui, |ui| {
66                        if let Some(ref item) = slot.item {
67                            ui.label(Vec2::new(5., 10.), &item);
68                        }
69                    });
70
71                match drag {
72                    // there is some item in this slot and it was dragged to another slot
73                    Drag::Dropped(_, Some(id)) if slot.item.is_some() => {
74                        *fit_command = Some(FittingCommand::Refit {
75                            target_slot: id,
76                            origin_slot: slot.id,
77                        });
78                    }
79                    // there is some item in this slot and it was dragged out - unfit it
80                    Drag::Dropped(_, None) if slot.item.is_some() => {
81                        *fit_command = Some(FittingCommand::Unfit {
82                            target_slot: slot.id,
83                        });
84                    }
85                    // there is no item in this slot
86                    // this is impossible - slots without items are non-draggable
87                    Drag::Dropped(_, _) => unreachable!(),
88                    Drag::Dragging(pos, id) => {
89                        debug!("slots: pos: {:?}, id {:?}", pos, id);
90                        *item_dragging = true;
91                    }
92                    Drag::No => {}
93                }
94                ui.label(Vec2::new(60., 20.), label);
95            });
96        }
97    }
98
99    fn inventory(&mut self, ui: &mut Ui) {
100        let item_dragging = &mut self.item_dragging;
101        for (n, item) in self.inventory.iter().enumerate() {
102            let drag = Group::new(hash!("inventory", n), Vec2::new(50., 50.))
103                .draggable(true)
104                .ui(ui, |ui| {
105                    ui.label(Vec2::new(5., 10.), &item);
106                });
107
108            match drag {
109                Drag::Dropped(_, Some(id)) => {
110                    self.fit_command = Some(FittingCommand::Fit {
111                        target_slot: id,
112                        item: item.clone(),
113                    });
114                    *item_dragging = false;
115                }
116                Drag::Dropped(_, _) => {
117                    *item_dragging = false;
118                }
119                Drag::Dragging(pos, id) => {
120                    debug!("inventory: pos: {:?}, id {:?}", pos, id);
121                    *item_dragging = true;
122                }
123                _ => {}
124            }
125        }
126    }
127
128    fn set_item(&mut self, id: u64, item: Option<String>) {
129        if let Some(slot) = self.slots.iter_mut().find(|(_, slot)| slot.id == id) {
130            slot.1.item = item;
131        }
132    }
133}
134
135#[macroquad::main("UI showcase")]
136async fn main() {
137    let mut data = Data::new();
138
139    let mut data0 = String::new();
140    let mut data1 = String::new();
141
142    let mut text0 = String::new();
143    let mut text1 = String::new();
144
145    let mut number0 = 0.;
146    let mut number1 = 0.;
147
148    let texture: Texture2D = load_texture("examples/ferris.png").await.unwrap();
149
150    loop {
151        clear_background(WHITE);
152
153        widgets::Window::new(hash!(), vec2(400., 200.), vec2(320., 400.))
154            .label("Shop")
155            .titlebar(true)
156            .ui(&mut *root_ui(), |ui| {
157                for i in 0..30 {
158                    Group::new(hash!("shop", i), Vec2::new(300., 80.)).ui(ui, |ui| {
159                        ui.label(Vec2::new(10., 10.), &format!("Item N {i}"));
160                        ui.label(Vec2::new(260., 40.), "10/10");
161                        ui.label(Vec2::new(200., 58.), &format!("{} kr", 800));
162                        if ui.button(Vec2::new(260., 55.), "buy") {
163                            data.inventory.push(format!("Item {i}"));
164                        }
165                    });
166                }
167            });
168
169        widgets::Window::new(hash!(), vec2(100., 220.), vec2(542., 430.))
170            .label("Fitting window")
171            .titlebar(true)
172            .ui(&mut *root_ui(), |ui| {
173                Group::new(hash!(), Vec2::new(230., 400.)).ui(ui, |ui| {
174                    data.slots(ui);
175                });
176                Group::new(hash!(), Vec2::new(280., 400.)).ui(ui, |ui| {
177                    data.inventory(ui);
178                });
179            });
180
181        widgets::Window::new(hash!(), vec2(470., 50.), vec2(300., 300.))
182            .label("Megaui Showcase Window")
183            .ui(&mut *root_ui(), |ui| {
184                ui.tree_node(hash!(), "input", |ui| {
185                    ui.label(None, "Some random text");
186                    if ui.button(None, "click me") {
187                        println!("hi");
188                    }
189
190                    ui.separator();
191
192                    ui.label(None, "Some other random text");
193                    if ui.button(None, "other button") {
194                        println!("hi2");
195                    }
196
197                    ui.separator();
198
199                    ui.input_text(hash!(), "<- input text 1", &mut data0);
200                    ui.input_text(hash!(), "<- input text 2", &mut data1);
201                    ui.label(None, &format!("Text entered: \"{data0}\" and \"{data1}\""));
202
203                    ui.separator();
204                });
205                ui.tree_node(hash!(), "buttons", |ui| {
206                    widgets::Button::new(texture.clone())
207                        .size(vec2(120., 70.))
208                        .ui(ui);
209                    ui.same_line(0.);
210                    widgets::Button::new("Button").size(vec2(120., 70.)).ui(ui);
211                    widgets::Button::new("Button").size(vec2(120., 70.)).ui(ui);
212                    ui.same_line(0.);
213                    widgets::Button::new(texture.clone())
214                        .size(vec2(120., 70.))
215                        .ui(ui);
216                });
217                ui.tree_node(hash!(), "sliders", |ui| {
218                    ui.slider(hash!(), "[-10 .. 10]", -10f32..10f32, &mut number0);
219                    ui.slider(hash!(), "[0 .. 100]", 0f32..100f32, &mut number1);
220                });
221                ui.tree_node(hash!(), "editbox 1", |ui| {
222                    ui.label(None, "This is editbox!");
223                    ui.editbox(hash!(), vec2(285., 165.), &mut text0);
224                });
225                ui.tree_node(hash!(), "editbox 2", |ui| {
226                    ui.label(None, "This is editbox!");
227                    ui.editbox(hash!(), vec2(285., 165.), &mut text1);
228                });
229            });
230
231        match data.fit_command.take() {
232            Some(FittingCommand::Unfit { target_slot }) => data.set_item(target_slot, None),
233            Some(FittingCommand::Fit { target_slot, item }) => {
234                data.set_item(target_slot, Some(item));
235            }
236            Some(FittingCommand::Refit {
237                target_slot,
238                origin_slot,
239            }) => {
240                let origin_item = data
241                    .slots
242                    .iter()
243                    .find_map(|(_, slot)| {
244                        if slot.id == origin_slot {
245                            Some(slot.item.clone())
246                        } else {
247                            None
248                        }
249                    })
250                    .flatten();
251                data.set_item(target_slot, origin_item);
252                data.set_item(origin_slot, None);
253            }
254            None => {}
255        };
256
257        next_frame().await;
258    }
259}
Source

pub const fn splat(v: f32) -> Vec2

Creates a vector with all elements set to v.

Source

pub fn select(mask: BVec2, if_true: Vec2, if_false: Vec2) -> Vec2

Creates a vector from the elements in if_true and if_false, selecting which to use for each element of self.

A true element in the mask uses the corresponding element from if_true, and false uses the element from if_false.

Source

pub const fn from_array(a: [f32; 2]) -> Vec2

Creates a new vector from an array.

Source

pub const fn to_array(&self) -> [f32; 2]

[x, y]

Source

pub const fn from_slice(slice: &[f32]) -> Vec2

Creates a vector from the first 2 values in slice.

§Panics

Panics if slice is less than 2 elements long.

Source

pub fn write_to_slice(self, slice: &mut [f32])

Writes the elements of self to the first 2 elements in slice.

§Panics

Panics if slice is less than 2 elements long.

Source

pub const fn extend(self, z: f32) -> Vec3

Creates a 3D vector from self and the given z value.

Source

pub fn with_x(self, x: f32) -> Vec2

Creates a 2D vector from self with the given value of x.

Source

pub fn with_y(self, y: f32) -> Vec2

Creates a 2D vector from self with the given value of y.

Source

pub fn dot(self, rhs: Vec2) -> f32

Computes the dot product of self and rhs.

Source

pub fn dot_into_vec(self, rhs: Vec2) -> Vec2

Returns a vector where every component is the dot product of self and rhs.

Source

pub fn min(self, rhs: Vec2) -> Vec2

Returns a vector containing the minimum values for each element of self and rhs.

In other words this computes [self.x.min(rhs.x), self.y.min(rhs.y), ..].

Source

pub fn max(self, rhs: Vec2) -> Vec2

Returns a vector containing the maximum values for each element of self and rhs.

In other words this computes [self.x.max(rhs.x), self.y.max(rhs.y), ..].

Source

pub fn clamp(self, min: Vec2, max: Vec2) -> Vec2

Component-wise clamping of values, similar to f32::clamp.

Each element in min must be less-or-equal to the corresponding element in max.

§Panics

Will panic if min is greater than max when glam_assert is enabled.

Source

pub fn min_element(self) -> f32

Returns the horizontal minimum of self.

In other words this computes min(x, y, ..).

Source

pub fn max_element(self) -> f32

Returns the horizontal maximum of self.

In other words this computes max(x, y, ..).

Source

pub fn element_sum(self) -> f32

Returns the sum of all elements of self.

In other words, this computes self.x + self.y + ...

Source

pub fn element_product(self) -> f32

Returns the product of all elements of self.

In other words, this computes self.x * self.y * ...

Source

pub fn cmpeq(self, rhs: Vec2) -> BVec2

Returns a vector mask containing the result of a == comparison for each element of self and rhs.

In other words, this computes [self.x == rhs.x, self.y == rhs.y, ..] for all elements.

Source

pub fn cmpne(self, rhs: Vec2) -> BVec2

Returns a vector mask containing the result of a != comparison for each element of self and rhs.

In other words this computes [self.x != rhs.x, self.y != rhs.y, ..] for all elements.

Source

pub fn cmpge(self, rhs: Vec2) -> BVec2

Returns a vector mask containing the result of a >= comparison for each element of self and rhs.

In other words this computes [self.x >= rhs.x, self.y >= rhs.y, ..] for all elements.

Source

pub fn cmpgt(self, rhs: Vec2) -> BVec2

Returns a vector mask containing the result of a > comparison for each element of self and rhs.

In other words this computes [self.x > rhs.x, self.y > rhs.y, ..] for all elements.

Source

pub fn cmple(self, rhs: Vec2) -> BVec2

Returns a vector mask containing the result of a <= comparison for each element of self and rhs.

In other words this computes [self.x <= rhs.x, self.y <= rhs.y, ..] for all elements.

Source

pub fn cmplt(self, rhs: Vec2) -> BVec2

Returns a vector mask containing the result of a < comparison for each element of self and rhs.

In other words this computes [self.x < rhs.x, self.y < rhs.y, ..] for all elements.

Source

pub fn abs(self) -> Vec2

Returns a vector containing the absolute value of each element of self.

Source

pub fn signum(self) -> Vec2

Returns a vector with elements representing the sign of self.

  • 1.0 if the number is positive, +0.0 or INFINITY
  • -1.0 if the number is negative, -0.0 or NEG_INFINITY
  • NAN if the number is NAN
Source

pub fn copysign(self, rhs: Vec2) -> Vec2

Returns a vector with signs of rhs and the magnitudes of self.

Source

pub fn is_negative_bitmask(self) -> u32

Returns a bitmask with the lowest 2 bits set to the sign bits from the elements of self.

A negative element results in a 1 bit and a positive element in a 0 bit. Element x goes into the first lowest bit, element y into the second, etc.

Source

pub fn is_finite(self) -> bool

Returns true if, and only if, all elements are finite. If any element is either NaN, positive or negative infinity, this will return false.

Source

pub fn is_nan(self) -> bool

Returns true if any elements are NaN.

Source

pub fn is_nan_mask(self) -> BVec2

Performs is_nan on each element of self, returning a vector mask of the results.

In other words, this computes [x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()].

Source

pub fn length(self) -> f32

Computes the length of self.

Examples found in repository?
examples/asteroids.rs (line 137)
46async fn main() {
47    let mut ship = Ship {
48        pos: Vec2::new(screen_width() / 2., screen_height() / 2.),
49        rot: 0.,
50        vel: Vec2::new(0., 0.),
51    };
52
53    let mut bullets = Vec::new();
54    let mut last_shot = get_time();
55    let mut asteroids = Vec::new();
56    let mut gameover = false;
57
58    let mut screen_center;
59
60    loop {
61        if gameover {
62            clear_background(LIGHTGRAY);
63            let mut text = "You Win!. Press [enter] to play again.";
64            let font_size = 30.;
65
66            if asteroids.len() > 0 {
67                text = "Game Over. Press [enter] to play again.";
68            }
69            let text_size = measure_text(text, None, font_size as _, 1.0);
70            draw_text(
71                text,
72                screen_width() / 2. - text_size.width / 2.,
73                screen_height() / 2. - text_size.height / 2.,
74                font_size,
75                DARKGRAY,
76            );
77            if is_key_down(KeyCode::Enter) {
78                ship = Ship {
79                    pos: Vec2::new(screen_width() / 2., screen_height() / 2.),
80                    rot: 0.,
81                    vel: Vec2::new(0., 0.),
82                };
83                bullets = Vec::new();
84                asteroids = Vec::new();
85                gameover = false;
86                screen_center = Vec2::new(screen_width() / 2., screen_height() / 2.);
87                for _ in 0..10 {
88                    asteroids.push(Asteroid {
89                        pos: screen_center
90                            + Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.))
91                                .normalize()
92                                * screen_width().min(screen_height())
93                                / 2.,
94                        vel: Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.)),
95                        rot: 0.,
96                        rot_speed: rand::gen_range(-2., 2.),
97                        size: screen_width().min(screen_height()) / 10.,
98                        sides: rand::gen_range(3, 8),
99                        collided: false,
100                    })
101                }
102            }
103            next_frame().await;
104            continue;
105        }
106        let frame_t = get_time();
107        let rotation = ship.rot.to_radians();
108
109        let mut acc = -ship.vel / 100.; // Friction
110
111        // Forward
112        if is_key_down(KeyCode::Up) {
113            acc = Vec2::new(rotation.sin(), -rotation.cos()) / 3.;
114        }
115
116        // Shot
117        if is_key_down(KeyCode::Space) && frame_t - last_shot > 0.5 {
118            let rot_vec = Vec2::new(rotation.sin(), -rotation.cos());
119            bullets.push(Bullet {
120                pos: ship.pos + rot_vec * SHIP_HEIGHT / 2.,
121                vel: rot_vec * 7.,
122                shot_at: frame_t,
123                collided: false,
124            });
125            last_shot = frame_t;
126        }
127
128        // Steer
129        if is_key_down(KeyCode::Right) {
130            ship.rot += 5.;
131        } else if is_key_down(KeyCode::Left) {
132            ship.rot -= 5.;
133        }
134
135        // Euler integration
136        ship.vel += acc;
137        if ship.vel.length() > 5. {
138            ship.vel = ship.vel.normalize() * 5.;
139        }
140        ship.pos += ship.vel;
141        ship.pos = wrap_around(&ship.pos);
142
143        // Move each bullet
144        for bullet in bullets.iter_mut() {
145            bullet.pos += bullet.vel;
146        }
147
148        // Move each asteroid
149        for asteroid in asteroids.iter_mut() {
150            asteroid.pos += asteroid.vel;
151            asteroid.pos = wrap_around(&asteroid.pos);
152            asteroid.rot += asteroid.rot_speed;
153        }
154
155        // Bullet lifetime
156        bullets.retain(|bullet| bullet.shot_at + 1.5 > frame_t);
157
158        let mut new_asteroids = Vec::new();
159        for asteroid in asteroids.iter_mut() {
160            // Asteroid/ship collision
161            if (asteroid.pos - ship.pos).length() < asteroid.size + SHIP_HEIGHT / 3. {
162                gameover = true;
163                break;
164            }
165
166            // Asteroid/bullet collision
167            for bullet in bullets.iter_mut() {
168                if (asteroid.pos - bullet.pos).length() < asteroid.size {
169                    asteroid.collided = true;
170                    bullet.collided = true;
171
172                    // Break the asteroid
173                    if asteroid.sides > 3 {
174                        new_asteroids.push(Asteroid {
175                            pos: asteroid.pos,
176                            vel: Vec2::new(bullet.vel.y, -bullet.vel.x).normalize()
177                                * rand::gen_range(1., 3.),
178                            rot: rand::gen_range(0., 360.),
179                            rot_speed: rand::gen_range(-2., 2.),
180                            size: asteroid.size * 0.8,
181                            sides: asteroid.sides - 1,
182                            collided: false,
183                        });
184                        new_asteroids.push(Asteroid {
185                            pos: asteroid.pos,
186                            vel: Vec2::new(-bullet.vel.y, bullet.vel.x).normalize()
187                                * rand::gen_range(1., 3.),
188                            rot: rand::gen_range(0., 360.),
189                            rot_speed: rand::gen_range(-2., 2.),
190                            size: asteroid.size * 0.8,
191                            sides: asteroid.sides - 1,
192                            collided: false,
193                        })
194                    }
195                    break;
196                }
197            }
198        }
199
200        // Remove the collided objects
201        bullets.retain(|bullet| bullet.shot_at + 1.5 > frame_t && !bullet.collided);
202        asteroids.retain(|asteroid| !asteroid.collided);
203        asteroids.append(&mut new_asteroids);
204
205        // You win?
206        if asteroids.len() == 0 {
207            gameover = true;
208        }
209
210        if gameover {
211            continue;
212        }
213
214        clear_background(LIGHTGRAY);
215
216        for bullet in bullets.iter() {
217            draw_circle(bullet.pos.x, bullet.pos.y, 2., BLACK);
218        }
219
220        for asteroid in asteroids.iter() {
221            draw_poly_lines(
222                asteroid.pos.x,
223                asteroid.pos.y,
224                asteroid.sides,
225                asteroid.size,
226                asteroid.rot,
227                2.,
228                BLACK,
229            )
230        }
231
232        let v1 = Vec2::new(
233            ship.pos.x + rotation.sin() * SHIP_HEIGHT / 2.,
234            ship.pos.y - rotation.cos() * SHIP_HEIGHT / 2.,
235        );
236        let v2 = Vec2::new(
237            ship.pos.x - rotation.cos() * SHIP_BASE / 2. - rotation.sin() * SHIP_HEIGHT / 2.,
238            ship.pos.y - rotation.sin() * SHIP_BASE / 2. + rotation.cos() * SHIP_HEIGHT / 2.,
239        );
240        let v3 = Vec2::new(
241            ship.pos.x + rotation.cos() * SHIP_BASE / 2. - rotation.sin() * SHIP_HEIGHT / 2.,
242            ship.pos.y + rotation.sin() * SHIP_BASE / 2. + rotation.cos() * SHIP_HEIGHT / 2.,
243        );
244        draw_triangle_lines(v1, v2, v3, 2., BLACK);
245
246        next_frame().await
247    }
248}
Source

pub fn length_squared(self) -> f32

Computes the squared length of self.

This is faster than length() as it avoids a square root operation.

Source

pub fn length_recip(self) -> f32

Computes 1.0 / length().

For valid results, self must not be of length zero.

Source

pub fn distance(self, rhs: Vec2) -> f32

Computes the Euclidean distance between two points in space.

Source

pub fn distance_squared(self, rhs: Vec2) -> f32

Compute the squared euclidean distance between two points in space.

Source

pub fn div_euclid(self, rhs: Vec2) -> Vec2

Returns the element-wise quotient of [Euclidean division] of self by rhs.

Source

pub fn rem_euclid(self, rhs: Vec2) -> Vec2

Returns the element-wise remainder of Euclidean division of self by rhs.

Source

pub fn normalize(self) -> Vec2

Returns self normalized to length 1.0.

For valid results, self must not be of length zero, nor very close to zero.

See also Self::try_normalize() and Self::normalize_or_zero().

Panics

Will panic if self is zero length when glam_assert is enabled.

Examples found in repository?
examples/asteroids.rs (line 91)
46async fn main() {
47    let mut ship = Ship {
48        pos: Vec2::new(screen_width() / 2., screen_height() / 2.),
49        rot: 0.,
50        vel: Vec2::new(0., 0.),
51    };
52
53    let mut bullets = Vec::new();
54    let mut last_shot = get_time();
55    let mut asteroids = Vec::new();
56    let mut gameover = false;
57
58    let mut screen_center;
59
60    loop {
61        if gameover {
62            clear_background(LIGHTGRAY);
63            let mut text = "You Win!. Press [enter] to play again.";
64            let font_size = 30.;
65
66            if asteroids.len() > 0 {
67                text = "Game Over. Press [enter] to play again.";
68            }
69            let text_size = measure_text(text, None, font_size as _, 1.0);
70            draw_text(
71                text,
72                screen_width() / 2. - text_size.width / 2.,
73                screen_height() / 2. - text_size.height / 2.,
74                font_size,
75                DARKGRAY,
76            );
77            if is_key_down(KeyCode::Enter) {
78                ship = Ship {
79                    pos: Vec2::new(screen_width() / 2., screen_height() / 2.),
80                    rot: 0.,
81                    vel: Vec2::new(0., 0.),
82                };
83                bullets = Vec::new();
84                asteroids = Vec::new();
85                gameover = false;
86                screen_center = Vec2::new(screen_width() / 2., screen_height() / 2.);
87                for _ in 0..10 {
88                    asteroids.push(Asteroid {
89                        pos: screen_center
90                            + Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.))
91                                .normalize()
92                                * screen_width().min(screen_height())
93                                / 2.,
94                        vel: Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.)),
95                        rot: 0.,
96                        rot_speed: rand::gen_range(-2., 2.),
97                        size: screen_width().min(screen_height()) / 10.,
98                        sides: rand::gen_range(3, 8),
99                        collided: false,
100                    })
101                }
102            }
103            next_frame().await;
104            continue;
105        }
106        let frame_t = get_time();
107        let rotation = ship.rot.to_radians();
108
109        let mut acc = -ship.vel / 100.; // Friction
110
111        // Forward
112        if is_key_down(KeyCode::Up) {
113            acc = Vec2::new(rotation.sin(), -rotation.cos()) / 3.;
114        }
115
116        // Shot
117        if is_key_down(KeyCode::Space) && frame_t - last_shot > 0.5 {
118            let rot_vec = Vec2::new(rotation.sin(), -rotation.cos());
119            bullets.push(Bullet {
120                pos: ship.pos + rot_vec * SHIP_HEIGHT / 2.,
121                vel: rot_vec * 7.,
122                shot_at: frame_t,
123                collided: false,
124            });
125            last_shot = frame_t;
126        }
127
128        // Steer
129        if is_key_down(KeyCode::Right) {
130            ship.rot += 5.;
131        } else if is_key_down(KeyCode::Left) {
132            ship.rot -= 5.;
133        }
134
135        // Euler integration
136        ship.vel += acc;
137        if ship.vel.length() > 5. {
138            ship.vel = ship.vel.normalize() * 5.;
139        }
140        ship.pos += ship.vel;
141        ship.pos = wrap_around(&ship.pos);
142
143        // Move each bullet
144        for bullet in bullets.iter_mut() {
145            bullet.pos += bullet.vel;
146        }
147
148        // Move each asteroid
149        for asteroid in asteroids.iter_mut() {
150            asteroid.pos += asteroid.vel;
151            asteroid.pos = wrap_around(&asteroid.pos);
152            asteroid.rot += asteroid.rot_speed;
153        }
154
155        // Bullet lifetime
156        bullets.retain(|bullet| bullet.shot_at + 1.5 > frame_t);
157
158        let mut new_asteroids = Vec::new();
159        for asteroid in asteroids.iter_mut() {
160            // Asteroid/ship collision
161            if (asteroid.pos - ship.pos).length() < asteroid.size + SHIP_HEIGHT / 3. {
162                gameover = true;
163                break;
164            }
165
166            // Asteroid/bullet collision
167            for bullet in bullets.iter_mut() {
168                if (asteroid.pos - bullet.pos).length() < asteroid.size {
169                    asteroid.collided = true;
170                    bullet.collided = true;
171
172                    // Break the asteroid
173                    if asteroid.sides > 3 {
174                        new_asteroids.push(Asteroid {
175                            pos: asteroid.pos,
176                            vel: Vec2::new(bullet.vel.y, -bullet.vel.x).normalize()
177                                * rand::gen_range(1., 3.),
178                            rot: rand::gen_range(0., 360.),
179                            rot_speed: rand::gen_range(-2., 2.),
180                            size: asteroid.size * 0.8,
181                            sides: asteroid.sides - 1,
182                            collided: false,
183                        });
184                        new_asteroids.push(Asteroid {
185                            pos: asteroid.pos,
186                            vel: Vec2::new(-bullet.vel.y, bullet.vel.x).normalize()
187                                * rand::gen_range(1., 3.),
188                            rot: rand::gen_range(0., 360.),
189                            rot_speed: rand::gen_range(-2., 2.),
190                            size: asteroid.size * 0.8,
191                            sides: asteroid.sides - 1,
192                            collided: false,
193                        })
194                    }
195                    break;
196                }
197            }
198        }
199
200        // Remove the collided objects
201        bullets.retain(|bullet| bullet.shot_at + 1.5 > frame_t && !bullet.collided);
202        asteroids.retain(|asteroid| !asteroid.collided);
203        asteroids.append(&mut new_asteroids);
204
205        // You win?
206        if asteroids.len() == 0 {
207            gameover = true;
208        }
209
210        if gameover {
211            continue;
212        }
213
214        clear_background(LIGHTGRAY);
215
216        for bullet in bullets.iter() {
217            draw_circle(bullet.pos.x, bullet.pos.y, 2., BLACK);
218        }
219
220        for asteroid in asteroids.iter() {
221            draw_poly_lines(
222                asteroid.pos.x,
223                asteroid.pos.y,
224                asteroid.sides,
225                asteroid.size,
226                asteroid.rot,
227                2.,
228                BLACK,
229            )
230        }
231
232        let v1 = Vec2::new(
233            ship.pos.x + rotation.sin() * SHIP_HEIGHT / 2.,
234            ship.pos.y - rotation.cos() * SHIP_HEIGHT / 2.,
235        );
236        let v2 = Vec2::new(
237            ship.pos.x - rotation.cos() * SHIP_BASE / 2. - rotation.sin() * SHIP_HEIGHT / 2.,
238            ship.pos.y - rotation.sin() * SHIP_BASE / 2. + rotation.cos() * SHIP_HEIGHT / 2.,
239        );
240        let v3 = Vec2::new(
241            ship.pos.x + rotation.cos() * SHIP_BASE / 2. - rotation.sin() * SHIP_HEIGHT / 2.,
242            ship.pos.y + rotation.sin() * SHIP_BASE / 2. + rotation.cos() * SHIP_HEIGHT / 2.,
243        );
244        draw_triangle_lines(v1, v2, v3, 2., BLACK);
245
246        next_frame().await
247    }
248}
Source

pub fn try_normalize(self) -> Option<Vec2>

Returns self normalized to length 1.0 if possible, else returns None.

In particular, if the input is zero (or very close to zero), or non-finite, the result of this operation will be None.

See also Self::normalize_or_zero().

Source

pub fn normalize_or(self, fallback: Vec2) -> Vec2

Returns self normalized to length 1.0 if possible, else returns a fallback value.

In particular, if the input is zero (or very close to zero), or non-finite, the result of this operation will be the fallback value.

See also Self::try_normalize().

Source

pub fn normalize_or_zero(self) -> Vec2

Returns self normalized to length 1.0 if possible, else returns zero.

In particular, if the input is zero (or very close to zero), or non-finite, the result of this operation will be zero.

See also Self::try_normalize().

Source

pub fn is_normalized(self) -> bool

Returns whether self is length 1.0 or not.

Uses a precision threshold of approximately 1e-4.

Source

pub fn project_onto(self, rhs: Vec2) -> Vec2

Returns the vector projection of self onto rhs.

rhs must be of non-zero length.

§Panics

Will panic if rhs is zero length when glam_assert is enabled.

Source

pub fn reject_from(self, rhs: Vec2) -> Vec2

Returns the vector rejection of self from rhs.

The vector rejection is the vector perpendicular to the projection of self onto rhs, in rhs words the result of self - self.project_onto(rhs).

rhs must be of non-zero length.

§Panics

Will panic if rhs has a length of zero when glam_assert is enabled.

Source

pub fn project_onto_normalized(self, rhs: Vec2) -> Vec2

Returns the vector projection of self onto rhs.

rhs must be normalized.

§Panics

Will panic if rhs is not normalized when glam_assert is enabled.

Source

pub fn reject_from_normalized(self, rhs: Vec2) -> Vec2

Returns the vector rejection of self from rhs.

The vector rejection is the vector perpendicular to the projection of self onto rhs, in rhs words the result of self - self.project_onto(rhs).

rhs must be normalized.

§Panics

Will panic if rhs is not normalized when glam_assert is enabled.

Source

pub fn round(self) -> Vec2

Returns a vector containing the nearest integer to a number for each element of self. Round half-way cases away from 0.0.

Source

pub fn floor(self) -> Vec2

Returns a vector containing the largest integer less than or equal to a number for each element of self.

Source

pub fn ceil(self) -> Vec2

Returns a vector containing the smallest integer greater than or equal to a number for each element of self.

Source

pub fn trunc(self) -> Vec2

Returns a vector containing the integer part each element of self. This means numbers are always truncated towards zero.

Source

pub fn fract(self) -> Vec2

Returns a vector containing the fractional part of the vector as self - self.trunc().

Note that this differs from the GLSL implementation of fract which returns self - self.floor().

Note that this is fast but not precise for large numbers.

Source

pub fn fract_gl(self) -> Vec2

Returns a vector containing the fractional part of the vector as self - self.floor().

Note that this differs from the Rust implementation of fract which returns self - self.trunc().

Note that this is fast but not precise for large numbers.

Source

pub fn exp(self) -> Vec2

Returns a vector containing e^self (the exponential function) for each element of self.

Source

pub fn powf(self, n: f32) -> Vec2

Returns a vector containing each element of self raised to the power of n.

Source

pub fn recip(self) -> Vec2

Returns a vector containing the reciprocal 1.0/n of each element of self.

Source

pub fn lerp(self, rhs: Vec2, s: f32) -> Vec2

Performs a linear interpolation between self and rhs based on the value s.

When s is 0.0, the result will be equal to self. When s is 1.0, the result will be equal to rhs. When s is outside of range [0, 1], the result is linearly extrapolated.

Source

pub fn move_towards(&self, rhs: Vec2, d: f32) -> Vec2

Moves towards rhs based on the value d.

When d is 0.0, the result will be equal to self. When d is equal to self.distance(rhs), the result will be equal to rhs. Will not go past rhs.

Source

pub fn midpoint(self, rhs: Vec2) -> Vec2

Calculates the midpoint between self and rhs.

The midpoint is the average of, or halfway point between, two vectors. a.midpoint(b) should yield the same result as a.lerp(b, 0.5) while being slightly cheaper to compute.

Source

pub fn abs_diff_eq(self, rhs: Vec2, max_abs_diff: f32) -> bool

Returns true if the absolute difference of all elements between self and rhs is less than or equal to max_abs_diff.

This can be used to compare if two vectors contain similar elements. It works best when comparing with a known value. The max_abs_diff that should be used used depends on the values being compared against.

For more see comparing floating point numbers.

Source

pub fn clamp_length(self, min: f32, max: f32) -> Vec2

Returns a vector with a length no less than min and no more than max

§Panics

Will panic if min is greater than max when glam_assert is enabled.

Source

pub fn clamp_length_max(self, max: f32) -> Vec2

Returns a vector with a length no more than max

Source

pub fn clamp_length_min(self, min: f32) -> Vec2

Returns a vector with a length no less than min

Source

pub fn mul_add(self, a: Vec2, b: Vec2) -> Vec2

Fused multiply-add. Computes (self * a) + b element-wise with only one rounding error, yielding a more accurate result than an unfused multiply-add.

Using mul_add may be more performant than an unfused multiply-add if the target architecture has a dedicated fma CPU instruction. However, this is not always true, and will be heavily dependant on designing algorithms with specific target hardware in mind.

Source

pub fn from_angle(angle: f32) -> Vec2

Creates a 2D vector containing [angle.cos(), angle.sin()]. This can be used in conjunction with the rotate() method, e.g. Vec2::from_angle(PI).rotate(Vec2::Y) will create the vector [-1, 0] and rotate Vec2::Y around it returning -Vec2::Y.

Source

pub fn to_angle(self) -> f32

Returns the angle (in radians) of this vector in the range [-π, +π].

The input does not need to be a unit vector however it must be non-zero.

Source

pub fn angle_between(self, rhs: Vec2) -> f32

Returns the angle (in radians) between self and rhs in the range [-π, +π].

The inputs do not need to be unit vectors however they must be non-zero.

Source

pub fn perp(self) -> Vec2

Returns a vector that is equal to self rotated by 90 degrees.

Source

pub fn perp_dot(self, rhs: Vec2) -> f32

The perpendicular dot product of self and rhs. Also known as the wedge product, 2D cross product, and determinant.

Source

pub fn rotate(self, rhs: Vec2) -> Vec2

Returns rhs rotated by the angle of self. If self is normalized, then this just rotation. This is what you usually want. Otherwise, it will be like a rotation with a multiplication by self’s length.

Source

pub fn as_dvec2(&self) -> DVec2

Casts all elements of self to f64.

Source

pub fn as_i16vec2(&self) -> I16Vec2

Casts all elements of self to i16.

Source

pub fn as_u16vec2(&self) -> U16Vec2

Casts all elements of self to u16.

Source

pub fn as_ivec2(&self) -> IVec2

Casts all elements of self to i32.

Source

pub fn as_uvec2(&self) -> UVec2

Casts all elements of self to u32.

Source

pub fn as_i64vec2(&self) -> I64Vec2

Casts all elements of self to i64.

Source

pub fn as_u64vec2(&self) -> U64Vec2

Casts all elements of self to u64.

Trait Implementations§

Source§

impl Add<f32> for Vec2

Source§

type Output = Vec2

The resulting type after applying the + operator.
Source§

fn add(self, rhs: f32) -> Vec2

Performs the + operation. Read more
Source§

impl Add for Vec2

Source§

type Output = Vec2

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Vec2) -> Vec2

Performs the + operation. Read more
Source§

impl AddAssign<f32> for Vec2

Source§

fn add_assign(&mut self, rhs: f32)

Performs the += operation. Read more
Source§

impl AddAssign for Vec2

Source§

fn add_assign(&mut self, rhs: Vec2)

Performs the += operation. Read more
Source§

impl AsMut<[f32; 2]> for Vec2

Source§

fn as_mut(&mut self) -> &mut [f32; 2]

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl AsRef<[f32; 2]> for Vec2

Source§

fn as_ref(&self) -> &[f32; 2]

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for Vec2

Source§

fn clone(&self) -> Vec2

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Vec2

Source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Vec2

Source§

fn default() -> Vec2

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Vec2

Source§

fn deserialize<D>( deserializer: D, ) -> Result<Vec2, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Vec2

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Div<f32> for Vec2

Source§

type Output = Vec2

The resulting type after applying the / operator.
Source§

fn div(self, rhs: f32) -> Vec2

Performs the / operation. Read more
Source§

impl Div for Vec2

Source§

type Output = Vec2

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Vec2) -> Vec2

Performs the / operation. Read more
Source§

impl DivAssign<f32> for Vec2

Source§

fn div_assign(&mut self, rhs: f32)

Performs the /= operation. Read more
Source§

impl DivAssign for Vec2

Source§

fn div_assign(&mut self, rhs: Vec2)

Performs the /= operation. Read more
Source§

impl From<[f32; 2]> for Vec2

Source§

fn from(a: [f32; 2]) -> Vec2

Converts to this type from the input type.
Source§

impl From<(f32, f32)> for Vec2

Source§

fn from(t: (f32, f32)) -> Vec2

Converts to this type from the input type.
Source§

impl From<BVec2> for Vec2

Source§

fn from(v: BVec2) -> Vec2

Converts to this type from the input type.
Source§

impl From<Vec2> for DVec2

Source§

fn from(v: Vec2) -> DVec2

Converts to this type from the input type.
Source§

impl Index<usize> for Vec2

Source§

type Output = f32

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &<Vec2 as Index<usize>>::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl IndexMut<usize> for Vec2

Source§

fn index_mut(&mut self, index: usize) -> &mut <Vec2 as Index<usize>>::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl Mul<Vec2> for Mat2

Source§

type Output = Vec2

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Vec2) -> <Mat2 as Mul<Vec2>>::Output

Performs the * operation. Read more
Source§

impl Mul<f32> for Vec2

Source§

type Output = Vec2

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: f32) -> Vec2

Performs the * operation. Read more
Source§

impl Mul for Vec2

Source§

type Output = Vec2

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Vec2) -> Vec2

Performs the * operation. Read more
Source§

impl MulAssign<f32> for Vec2

Source§

fn mul_assign(&mut self, rhs: f32)

Performs the *= operation. Read more
Source§

impl MulAssign for Vec2

Source§

fn mul_assign(&mut self, rhs: Vec2)

Performs the *= operation. Read more
Source§

impl Neg for Vec2

Source§

type Output = Vec2

The resulting type after applying the - operator.
Source§

fn neg(self) -> Vec2

Performs the unary - operation. Read more
Source§

impl PartialEq for Vec2

Source§

fn eq(&self, other: &Vec2) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a> Product<&'a Vec2> for Vec2

Source§

fn product<I>(iter: I) -> Vec2
where I: Iterator<Item = &'a Vec2>,

Takes an iterator and generates Self from the elements by multiplying the items.
Source§

impl Product for Vec2

Source§

fn product<I>(iter: I) -> Vec2
where I: Iterator<Item = Vec2>,

Takes an iterator and generates Self from the elements by multiplying the items.
Source§

impl Rem<f32> for Vec2

Source§

type Output = Vec2

The resulting type after applying the % operator.
Source§

fn rem(self, rhs: f32) -> Vec2

Performs the % operation. Read more
Source§

impl Rem for Vec2

Source§

type Output = Vec2

The resulting type after applying the % operator.
Source§

fn rem(self, rhs: Vec2) -> Vec2

Performs the % operation. Read more
Source§

impl RemAssign<f32> for Vec2

Source§

fn rem_assign(&mut self, rhs: f32)

Performs the %= operation. Read more
Source§

impl RemAssign for Vec2

Source§

fn rem_assign(&mut self, rhs: Vec2)

Performs the %= operation. Read more
Source§

impl Serialize for Vec2

Source§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Sub<f32> for Vec2

Source§

type Output = Vec2

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: f32) -> Vec2

Performs the - operation. Read more
Source§

impl Sub for Vec2

Source§

type Output = Vec2

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Vec2) -> Vec2

Performs the - operation. Read more
Source§

impl SubAssign<f32> for Vec2

Source§

fn sub_assign(&mut self, rhs: f32)

Performs the -= operation. Read more
Source§

impl SubAssign for Vec2

Source§

fn sub_assign(&mut self, rhs: Vec2)

Performs the -= operation. Read more
Source§

impl<'a> Sum<&'a Vec2> for Vec2

Source§

fn sum<I>(iter: I) -> Vec2
where I: Iterator<Item = &'a Vec2>,

Takes an iterator and generates Self from the elements by “summing up” the items.
Source§

impl Sum for Vec2

Source§

fn sum<I>(iter: I) -> Vec2
where I: Iterator<Item = Vec2>,

Takes an iterator and generates Self from the elements by “summing up” the items.
Source§

impl Vec2Swizzles for Vec2

Source§

type Vec3 = Vec3

Source§

type Vec4 = Vec4

Source§

fn xx(self) -> Vec2

Source§

fn xy(self) -> Vec2

Source§

fn yx(self) -> Vec2

Source§

fn yy(self) -> Vec2

Source§

fn xxx(self) -> Vec3

Source§

fn xxy(self) -> Vec3

Source§

fn xyx(self) -> Vec3

Source§

fn xyy(self) -> Vec3

Source§

fn yxx(self) -> Vec3

Source§

fn yxy(self) -> Vec3

Source§

fn yyx(self) -> Vec3

Source§

fn yyy(self) -> Vec3

Source§

fn xxxx(self) -> Vec4

Source§

fn xxxy(self) -> Vec4

Source§

fn xxyx(self) -> Vec4

Source§

fn xxyy(self) -> Vec4

Source§

fn xyxx(self) -> Vec4

Source§

fn xyxy(self) -> Vec4

Source§

fn xyyx(self) -> Vec4

Source§

fn xyyy(self) -> Vec4

Source§

fn yxxx(self) -> Vec4

Source§

fn yxxy(self) -> Vec4

Source§

fn yxyx(self) -> Vec4

Source§

fn yxyy(self) -> Vec4

Source§

fn yyxx(self) -> Vec4

Source§

fn yyxy(self) -> Vec4

Source§

fn yyyx(self) -> Vec4

Source§

fn yyyy(self) -> Vec4

Source§

impl Copy for Vec2

Source§

impl StructuralPartialEq for Vec2

Auto Trait Implementations§

§

impl Freeze for Vec2

§

impl RefUnwindSafe for Vec2

§

impl Send for Vec2

§

impl Sync for Vec2

§

impl Unpin for Vec2

§

impl UnwindSafe for Vec2

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T, Rhs> NumAssignOps<Rhs> for T
where T: AddAssign<Rhs> + SubAssign<Rhs> + MulAssign<Rhs> + DivAssign<Rhs> + RemAssign<Rhs>,

Source§

impl<T, Rhs, Output> NumOps<Rhs, Output> for T
where T: Sub<Rhs, Output = Output> + Mul<Rhs, Output = Output> + Div<Rhs, Output = Output> + Add<Rhs, Output = Output> + Rem<Rhs, Output = Output>,