[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上.

下次見!

相關文章
相關標籤/搜索