[MetalKit]39-Working-with-Particles-in-Metal粒子系统

本系列文章是对 metalkit.org 上面MetalKit内容的全面翻译和学习.c++

MetalKit系统文章目录git


今天,咱们将开始一个新系列,关于Metal中的粒子系统.绝大多数时间,粒子都是小物体,咱们老是不关心他们的几何形状.这让他们适合于使用计算着色器,由于稍后咱们将在粒子-粒子交互中使用粒度控制,这是一个用于展现经过计算着色器进行高度并行控制的例子.咱们使用上一次的playground,就是从环境光遮蔽那里开始.这个playground在这里很是有用,由于它已经有一个CPU传递到GPUtime变量.咱们从一个新的Shader.metal文件开始,给一个漂亮的背景色:github

#include <metal_stdlib>
using namespace metal;

kernel void compute(texture2d<float, access::write> output [[texture(0)]],
                    constant float &time [[buffer(0)]],
                    uint2 gid [[thread_position_in_grid]]) {
    int width = output.get_width();
    int height = output.get_height();
    float2 uv = float2(gid) / float2(width, height);
    output.write(float4(0.2, 0.5, 0.7, 1), gid);
}
复制代码

接着,让咱们建立一个粒子对象,只包含一个位置(中心)和半径:app

struct Particle {
    float2 center;
    float radius;
};
复制代码

咱们还须要一个方法来获取粒子在屏幕上的位置,那让咱们建立一个距离函数:函数

float distanceToParticle(float2 point, Particle p) {
    return length(point - p.center) - p.radius;
}
复制代码

在内核中,在最后一行上面,让咱们一个新的粒子并将其放置在屏幕顶部,X轴中间.设置半径为0.05:post

float2 center = float2(0.5, time);
float radius = 0.05;
Particle p = Particle{center, radius};
复制代码

注意:咱们使用time做为粒子的Y坐标,但这只是一个显示基本运动的小技巧.很快,咱们将用符合物理法则的坐标来替换这个变量.学习

用下面代码替换内核的最后一行,并运行app.你会看到粒子以固定速率掉落:ui

float distance = distanceToParticle(uv, p);
float4 color = float4(1, 0.7, 0, 1);
if (distance > 0) { color = float4(0.2, 0.5, 0.7, 1); }
output.write(float4(color), gid);
复制代码

然而,这个粒子将永远朝下运动.为了让它停在底部,在建立粒子以前使用下面的条件:spa

float stop = 1 - radius;
if (time >= stop) { center.y = stop; }
else center.y = time;
复制代码

注意:timeuv变量都在0-1范围内变化,这样咱们就建立一个stop点,它就在屏幕正方边缘一个粒子半径的位置.翻译

这是一个很是基本的碰撞检测规则.若是你运行app,你将会看到粒子掉落并停上底部,像这样:

particle.gif

下次,咱们将更深刻粒子动态效果,并实现物理运动法则.

源代码source code已发布在Github上.

下次见!

相关文章
相关标签/搜索