Cult3D 是一個能用來製作互動式 3D 產品的技術平台,其中「換色」是很常見的應用——例如讓使用者即時切換產品的顏色外觀。本文分享如何撰寫 Java 腳本,透過更換材質(texture)的方式來實現動態換色。
整體流程非常直覺:先定義一個新的顏色,再把這個顏色的變數名稱加入 colors 陣列,最後呼叫 changeColor 方法就能循環切換顏色。
例如定義一個紅色:
private Color red = new Color(198, 58, 41);
以下為完整的 ColorSwap 類別。關鍵在於 TEXTURE_NAME 要對應你想更換的材質名稱,而 RGB 數值範圍為 0 到 255(0 為黑、255 為白):
import com.cult3d.*;
import com.cult3d.world.*;
import java.awt.Color;
import java.awt.Image;
import java.awt.Graphics;
public class ColorSwap implements Cult3DScript, Runnable {
// TEXTURE_NAME 的值是你要改變的材質名稱
private static final String TEXTURE_NAME = "MADAROSE";
// 想增加更多顏色,就在這裡建立 Color 實例,並加入 colors 陣列
private Color red = new Color(198, 58, 41);
private Color blue = new Color(99, 93, 163);
private Color green = new Color(138, 149, 78);
private Color grey = new Color(136, 136, 136);
private Color lightBlue = new Color(121, 130, 173);
private Color black = new Color(64, 64, 64);
private Color[] colors = {red, blue, green, grey, lightBlue, black };
/////
private Texture texture;
private TextureImage textureImage;
private int textureWidth, textureHeight;
private Graphics graphics;
// 宣告為 volatile,確保變數值永遠正確
private volatile boolean loaded = false;
private int colorCounter = 0;
// 標準建構子
public ColorSwap() {
Thread thread = new Thread(this);
thread.start();
}
// 執行緒方法:載入較「重」的資源與材質,避免載入時畫面卡住
public void run() {
texture = new Texture(TEXTURE_NAME);
textureWidth = texture.getWidth();
textureHeight = texture.getHeight();
textureImage = (TextureImage)Cult.createImage(textureWidth, textureHeight);
graphics = textureImage.getGraphics();
loaded = true;
}
// 從 Designer 呼叫這個方法來循環切換顏色
public void changeColor(String s) {
if (!loaded) { System.out.println("The Java code is not yet loaded"); return; }
if (colorCounter >= colors.length) { colorCounter = 0; }
switchColor(colors[colorCounter]);
colorCounter++;
}
// 實際執行換色
private void switchColor(Color color) {
graphics.setColor(color);
graphics.fillRect(0,0, textureWidth,textureHeight);
texture.setTexture(textureImage);
}
public void cult3dDestroy() { }
}
程式透過一個獨立執行緒在背景載入材質,避免畫面卡頓;接著用 Graphics 填滿整個材質區域的顏色,再透過 texture.setTexture() 把新材質套回模型上。changeColor 每次被呼叫時會把 colorCounter 往前推進,到頭後再回到起點,形成循環換色的效果。