2

So I'm making a vertex shader to make a GameObject look like it's shrinking/expanding (pulsating?) continuously.

I am using a normal scale matrix to multiply the position of every vertex, but I want to keep the object appearing centered in the same position. If I could get the transform.position of the gameObject that is being rendered, I know I would be able to keep the center position the same.

So how would I access the gameobject's position in my CG shader?

Or am I approaching this problem incorrectly?

vertexOut vert(vertexIn v)
{
    vertexOut o;

    o.pos = mul(UNITY_MATRIX_MVP,v.vertex);
    o.pos2 = mul(UNITY_MATRIX_MVP,v.vertex);


    float scaleVal = sin(_Time.y*10)/8 + 1.0;
    float4x4 scaleMat = float4x4(
    scaleVal,   0, 0, 0,
    0,  scaleVal, 0, 0,
    0,  0, 1, 0,
    0, 0, 0, 1);

    o.pos = mul(scaleMat,o.pos);
    return o;
}
Teepeemm
  • 4,331
  • 5
  • 35
  • 58
Martin
  • 93
  • 1
  • 6

2 Answers2

3

Simply define a shader property of type Vector. Then you can update this property on every frame by calling SetVector on the material.

nwellnhof
  • 32,319
  • 7
  • 89
  • 113
0

Sounds like you just want to multiply v.vertex by your scaleMat. So something like:

vertexOut vert(vertexIn v)
{
    vertexOut o;

    o.pos2 = mul(UNITY_MATRIX_MVP,v.vertex);

    float scaleVal = sin(_Time.y*10)/8 + 1.0;
    float4x4 scaleMat = float4x4(
    scaleVal,   0, 0, 0,
    0,  scaleVal, 0, 0,
    0,  0, 1, 0,
    0, 0, 0, 1);

    o.pos = mul(UNITY_MATRIX_MVP, mul(scaleMat, v.vertex));
    return o;
}

Of course this might behave differently from what you want depending on how you want your mesh to behave under rotation.

To answer the actual posted question though, you can figure out what the transform's position is directly in the vertex shader by converting the origin to world space:

mul(unity_ObjectToWorld, float4(0,0,0,1)).xyz

Marplebot
  • 61
  • 5