跳到主要内容

动态纹理

查看完整项目。

让表面材质产生动画非常实用。本例通过滚动纹理模拟运动。

使用贴图偏移滚动材质​

示例中的方形平面通过 scrolling-texture.js 脚本每帧持续移动 UV 偏移,例如可以用来模拟流水。更新循环如下。

ScrollingTexture.prototype.update = function(dt) {
var velocity = ScrollingTexture.tmpVec2;
var offset = ScrollingTexture.tmpOffset;

// Calculate how much to offset the texture
// Speed * dt
velocity.set(this.speed.x, this.speed.y);
velocity.scale(dt);

// Update the diffuse and normal map offset values
offset.copy(this.material.diffuseMapOffset);
offset.add(velocity);

this.material.diffuseMapOffset = offset;
this.material.normalMapOffset = offset;
this.material.update();
};

首先将所需偏移计算到临时向量 tmp 中,即 speed * timeStep。接着修改 diffuseMapOffset 和 normalMapOffset,把该偏移加到漫反射贴图与法线贴图的偏移属性上。这些 pc.Vec2 值会平移纹理映射到表面时使用的 UV 坐标。如果使用了自发光等其他贴图,也需要同步更新它们的偏移属性。最后调用 material.update(),将修改应用到着色器。

这种通过材质偏移滚动纹理的方法简单直接,但它会修改实际材质的属性,因此场景中所有使用同一材质的模型都会受到影响。