【问题标题】:unity - texture scroll speed with gameobjectunity - 游戏对象的纹理滚动速度
【发布时间】:2016-11-03 02:24:48
【问题描述】:

我有一个 unity3D 板,板上有一个立方体。板的纹理和纹理偏移按 Y 坐标变化,因此看起来像是向后移动。立方体也应该以与板的偏移相同的速度移动,但我无法在它们之间设置相同的速度。

我的板子滚动代码:

public class moveBoard : MonoBehaviour
{

// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void Update ()
{

    this.GetComponent<MeshRenderer>().material.SetTextureOffset("_MainTex", new Vector2(0, -1 * Time.time));
}
}

还有我的立方体移动代码:

public class moveTus : MonoBehaviour
{
public GameObject board;
float offsetY = 0f;
// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void Update ()
{
    this.transform.Translate(Vector3.back * -10 * Time.deltaTime) ;
}
}

所以我需要以与板偏移速度相同的速度移动立方体。

【问题讨论】:

    标签: unity3d scroll textures offset


    【解决方案1】:

    在两个脚本中都包含一个公共速度变量。

    public class moveBoard : MonoBehaviour { public float speed=1; void Update () { this.GetComponent().material.SetTextureOffset("_MainTex", new Vector2(0, -1 * Time.deltaTime * speed * UserOptions.speed)); } }

    公共类 moveTus : MonoBehaviour { 公共浮动速度=1; 无效更新() { this.transform.Translate(Vector3.back * -10 * Time.deltaTime * speed * UserOptions.speed) ; } }

    在运行时尝试通过在编辑器检查器中手动更改任何这些速度变量值来进行同步。在找到它们之间的微调后,在设计时应用这些值。

    【讨论】:

    • 您是对的,但用户将能够在游戏选项中更改速度变量。所以他们之间应该有一个完美的比率,否则我不能用我的眼睛找到它。
    • 你需要一个静态变量来保存用户选择的速度。你冷乘这两个速度。无论如何,您必须先找到此同步。
    • 即使您之前找到了同步速度,如果您更改可选速度,则必须更改同步变量,否则我们将再次看到差异。
    • 我的意思是向用户公开的第三个(静态)变量。这个变量应该乘以我建议的两个速度。如果它是同步一次,它将永远是好的。我更新了代码,看看吧。
    【解决方案2】:

    我今天需要相同的功能。所以这是我的代码

        List<Vector2> uvs = new List<Vector2>();
        groundMesh.GetComponent<MeshFilter>().mesh.GetUVs( 0 , uvs ); // get uv coordinates
    
        float min = float.MaxValue;
        float max = float.MinValue;
    
        foreach ( var item in uvs ) // find min and max
        {
            if ( item.x > max )
            {
                max = item.x;
            }
    
            if ( item.x < min )
            {
                min = item.x;
            }
        }
    
        groundUV_X = Mathf.Abs( min - max ); // find absolute value
    

    我的固定更新代码:

     var v = groundMaterial.GetTextureOffset( "_MainTex" ); // get current offset
            groundMaterial.SetTextureOffset( "_MainTex" , new Vector2( v.x + ( speed * Time.fixedDeltaTime * groundUV_X) * (1.0f / groundMesh.bounds.size.z) , v.y ) ); 
    // multiply speed by groundUV_X which is total distance between x coordinates
    // multiply by world size (normalized total distance)
    

    获取最小和最大 uv 坐标(在我的例子中是 x 坐标)并乘以速度。 因为我们需要世界坐标中的纹理大小(在我的例子中是 bounds.size.z) 将其标准化 1。然后我们得到了同步坐标。

    如果有人不能让它工作,请告诉我。我可以添加更多细节。

    【讨论】:

    • 能否补充一下,如何获取groundMeshgroundMaterial...?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多