You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bevy v0.13中如何为Plane3d创建带指定细分的网格?

在Bevy v0.13中基于Plane3d创建带指定细分的网格

在Bevy v0.13中,原shape::Plane被废弃,新的Plane3d仅用于定义平面的数学属性(如法线、原点、坐标轴),本身不提供细分参数。要创建带指定细分数量的平面网格,需要手动生成顶点、UV和索引数据,再构建Mesh对象。

实现方法

下面是一个可复用的函数,接收Plane3d、平面尺寸和细分数量,返回对应的网格:

use bevy_math::Plane3d;
use bevy_render::mesh::{Mesh, VertexAttributeValues};
use bevy_render::render_resource::PrimitiveTopology;

fn create_subdivided_plane(plane: Plane3d, size: f32, subdivisions: u32) -> Mesh {
    let half_size = size / 2.0;
    let step = size / subdivisions as f32;

    // 生成顶点位置与UV坐标
    let mut positions = Vec::new();
    let mut uvs = Vec::new();
    for z in 0..=subdivisions {
        for x in 0..=subdivisions {
            // 计算局部平面内的坐标
            let x_pos = -half_size + x as f32 * step;
            let z_pos = -half_size + z as f32 * step;
            // 转换到Plane3d定义的空间中
            let position = plane.origin() + plane.x_axis() * x_pos + plane.z_axis() * z_pos;
            positions.push(position.to_array());

            // 生成UV坐标
            let u = x as f32 / subdivisions as f32;
            let v = z as f32 / subdivisions as f32;
            uvs.push([u, v]);
        }
    }

    // 生成三角面索引
    let mut indices = Vec::new();
    for z in 0..subdivisions {
        for x in 0..subdivisions {
            let base_idx = z * (subdivisions + 1) + x;
            indices.extend_from_slice(&[
                base_idx, base_idx + 1, base_idx + subdivisions + 1,
                base_idx + 1, base_idx + subdivisions + 2, base_idx + subdivisions + 1,
            ]);
        }
    }

    // 构建Mesh对象
    let mut mesh = Mesh::new(PrimitiveTopology::TriangleList);
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, VertexAttributeValues::Float32x3(positions));
    mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, VertexAttributeValues::Float32x2(uvs));
    mesh.set_indices(Some(bevy_render::mesh::Indices::U32(indices)));

    mesh
}

使用示例

你可以根据需要指定平面方向(比如Plane3d::xy()、Plane3d::xz()或Plane3d::yz()),并传入尺寸和细分数量:

use bevy_math::Plane3d;

// 创建XZ平面,尺寸160,细分15(与v0.12的示例效果一致)
let plane = Plane3d::xz();
let mesh = create_subdivided_plane(plane, 160.0, 15);

说明

  • Plane3d的x_axis()和z_axis()方法提供了平面内的两个正交轴,用于构建网格的顶点位置
  • 函数中生成的UV坐标从(0,0)到(1,1),适配常规纹理映射需求
  • 索引采用三角列表拓扑,确保平面网格正确渲染

内容的提问来源于stack exchange,提问作者Claudijo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 09:16:13