I want to make a simple ray marching loop in the fragment shader. I think the main issue is that I'm not giving the correct world position input.

Here is my current attempt:

_MainTex ("Texture", 2D) = "white" {}

#pragma vertex vert    
#pragma fragment frag

#include "UnityCG.cginc"
#include "HLSLSupport.cginc"

int steps = 64;
float3 centre = float3(0,0,0);
float radius = 1.0;
sampler2D _MainTex;

float sph(float3 posi){
    return distance(posi, centre) - radius;

struct v2f{
    float4 vertex : SV_POSITION;
    float3 wpos : TEXCOORD0;

struct appdata{
    float4 vertex : POSITION;

v2f vert(appdata v){
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);
    o.wpos = mul(unity_ObjectToWorld, v.vertex).xyz;
    return o;

fixed4 frag(v2f i) : SV_TARGET{
    float3 wpos = mul(unity_ObjectToWorld, i.wpos).xyz;
    float t = 0;
    float3 dir = normalize(wpos - _WorldSpaceCameraPos);
    fixed4 col;

    for (int j = 0; j < steps; j++){
        if (t > 100){
            col = fixed4(0, 0, 0, 1);
        float3 p = wpos + dir * t;
        float d = sph(p);
        if (d < 0.001){
            col = fixed4(1, 0, 0, 1);
        t += d;
    return col;

The output of this code is always black.

enter image description here

Also, wpos is supposed to be the world position of the pixels.

New contributor
Nikhil Nair is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • \$\begingroup\$ Can you copy and paste the code instead of a screenshot, please? Also, if you have any more details, that would be useful to help you. \$\endgroup\$
    – Evorlor
  • 1
    \$\begingroup\$ Why are you multiplying by the object-to-world matrix twice, once in the vertex shader, and again in the fragment shader? \$\endgroup\$
    – DMGregory
  • \$\begingroup\$ @DMGregory I thought it returns the world position of the pixels. \$\endgroup\$ yesterday
  • \$\begingroup\$ That does not explain why you're doing it twice. \$\endgroup\$
    – DMGregory
    23 hours ago


You must log in to answer this question.

Browse other questions tagged .