not-fl3 / macroquad

Cross-platform game engine in Rust.
Apache License 2.0
3.35k stars 323 forks source link

How can I have a custom shape #174

Open Tros-t opened 3 years ago

Tros-t commented 3 years ago

In processing and p5.js there are things like beginShape() and endShape() and also vertex(x,y) which allow us to make our custom shapes how can i do that in macroquad.

I am new to this library and rust but Love how kind of simple this thing is.

If you know the answer to my question, kindly give me an example by drawing a square with something like begin shape and endshape.

It will be really helpful. Thanks in Advance :D

tirithen commented 3 years ago

@Saad-py not sure if this is good enough for your case, but I created a draw_polygon function for a project I'm working on. I supply

use macroquad::{math::*, models::*, prelude::Color};

pub fn draw_polygon(x: f32, y: f32, points: Vec<Vec2>, color: Color) {
    let points_length = points.len();
    let mut vertices = Vec::<Vertex>::with_capacity(points_length as usize + 2);
    let mut indices = Vec::<u16>::with_capacity(points_length as usize * 3);

    for (i, point) in points.iter().enumerate() {
        let vertex = Vertex {
            position: Vec3::new(x + point.x, y + point.y, 0.0),
            uv: Vec2::default(),
            color
        };

        vertices.push(vertex);
        indices.extend_from_slice(&[0, i as u16 + 1, i as u16 + 2]);
    }

    let mesh = Mesh {
        vertices,
        indices,
        texture: None,
    };

    draw_mesh(&mesh);
}

Just pass the function a Vec with 2D points as the third argument.

I'm also fairly new to on using this project so there might be even better ways.