如何手动创建带有顶点的网格?

问题描述

我需要做什么才能为具有以下顶点的 bevy 创建网格:

let mut vertices : Vec<[f32; 3]> = Vec::new();

    vertices.push([0.0,0.0,0.0]);
    vertices.push([1.0,2.0,1.0]);
    vertices.push([2.0,0.0]);

然后我想像这样生成一个 MeshBundle

commands
    .spawn(MeshBundle {
        mesh: mesh,transform: Transform::from_translation(Vec3::new(0.0,0.0)),..Default::default()
    });

解决方法

您的问题缺少很多细节,例如您使用的是哪个版本的 bevy,您定义了哪些着色器等。

我仍在尝试为 bevy = 0.4 和默认着色器提供答案。

以下代码演示了如何

  1. bevy::render::pipeline::PrimitiveTopology::TriangleList 定义顶点(因为我怀疑您正在尝试这样做...)
  2. 顶点法线分配给位置
  3. uv坐标分配给位置

它很大程度上基于 bevy 中的内置形状,可以在 here 中找到。

use bevy::prelude::*;

fn main() {
    App::build()
        .add_resource(Msaa { samples: 4 })
        .add_plugins(DefaultPlugins)
        .add_startup_system(setup.system())
        .run();
}

/// set up a simple 3D scene
fn setup(
    commands: &mut Commands,mut meshes: ResMut<Assets<Mesh>>,mut materials: ResMut<Assets<StandardMaterial>>,) {
    let vertices = [
        ([0.0,0.0,0.0],[0.0,1.0,[1.0,1.0]),([1.0,2.0,1.0],([2.0,];

    let indices = bevy::render::mesh::Indices::U32(vec![0,2,1,3,2]);

    let mut positions = Vec::new();
    let mut normals = Vec::new();
    let mut uvs = Vec::new();
    for (position,normal,uv) in vertices.iter() {
        positions.push(*position);
        normals.push(*normal);
        uvs.push(*uv);
    }

    let mut mesh = Mesh::new(bevy::render::pipeline::PrimitiveTopology::TriangleList);
    mesh.set_indices(Some(indices));
    mesh.set_attribute(Mesh::ATTRIBUTE_POSITION,positions);
    mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL,normals);
    mesh.set_attribute(Mesh::ATTRIBUTE_UV_0,uvs);

    // add entities to the world
    commands
        // plane
        .spawn(PbrBundle {
            mesh: meshes.add(mesh),material: materials.add(Color::rgb(0.3,0.5,0.3).into()),..Default::default()
        })
        // light
        .spawn(LightBundle {
            transform: Transform::from_translation(Vec3::new(4.0,8.0,4.0)),..Default::default()
        })
        // camera
        .spawn(Camera3dBundle {
            transform: Transform::from_translation(Vec3::new(-2.0,2.5,5.0))
                .looking_at(Vec3::default(),Vec3::unit_y()),..Default::default()
        });
}

显然,您必须以这样的方式定义 positionsuvsnormals,以便它们对您的用例有意义。除此之外,根据您的着色器,您可能不需要所有这些网格属性。