我如何在世界单元中设置纹理的滚动速度



我正在尝试制作一个无限的跑步者,其中来自屏幕侧面的对象。但是,物体的速度与地板纹理的速度不符。

public GameObject floorPrefab;
public GameObject g;
float floorSpeed = 3.0;

void FixedUpdate () {
    //Floor
    floorSpeed += 0.001f;
    floorPrefab.GetComponent<Renderer>().material.mainTextureOffset += new Vector2(floorSpeed * Time.fixedDeltaTime, 0.0f);
    //GameObject
    g.transform.Translate(-Vector2.right * floorSpeed * Time.fixedDeltaTime);
}

对象和材料应以x方向以相同的速度行驶。

我的地板是Quad,其MeshRenderer沿x方向瓷砖17次。

mainTextureOffset在UV单元中,Translate使用世界空间单位。您需要一种在它们之间转换的方法。

首先,您需要知道您的渲染器渲染长多少个UV单元。这将等同于它一次显示的纹理的一部分,或在渲染器上重复多少次。

uVcount = 17f; // repeats 17 times in the scrolling direction

然后,您需要知道渲染器在世界单位中(在滚动方向上(有多长时间。因为您的渲染器是轴对齐的,所以这变得很容易,因为我们可以使用renderer.bounds.size查找网格的音量,然后找到renderer.bounds.size.x以找到长度。

Renderer rend = floorPrefab.GetComponent<Renderer>();
float rendererLength = rend.bounds.size.x;

所以现在剩下的就是将floorSpeed从每fixedUpdate转换为每fixedUpdate的UV单元,然后将其用作您的偏移变化的数量:

float floorSpeedUV = floorSpeed  * uVcount / rendererLength;
rend.material.mainTextureOffset += new Vector2(floorSpeedUV * Time.fixedDeltaTime, 0.0f);

完全看起来像这样:

public GameObject floorPrefab;
public GameObject g;
public float uVcount = 7f; // repeats 7 times in the scrolling direction
float floorSpeed = 3.0;
private Renderer rend;
private float rendererLength;
void Start () {
    rend = floorPrefab.GetComponent<Renderer>();
    rendererLength = rend.bounds.size.x;
}
void FixedUpdate () {
    //Floor
    floorSpeed += 0.001f;
    float floorSpeedUV = floorSpeed  * uVcount / rendererLength;
    rend.material.mainTextureOffset += new Vector2(floorSpeedUV * Time.fixedDeltaTime, 0.0f);
    //GameObject
    g.transform.Translate(-Vector2.right * floorSpeed * Time.fixedDeltaTime);
}

最新更新