当您以RTS游戏或Windows桌面的方式单击和拖动时,我正在尝试绘制一个选择框。目前,当我运行此代码时,它会在中心创建一个带有透明菱形的绿色框。
我正在尝试创建一个带有实心1px边框和内部略透明的框。
public class SelectionBox : MonoBehaviour {
public Color borderColor = new Color(0f, 1f, 0f, 1f);
public Color innerColor = new Color(0f, 1f, 0f, 0.2f);
bool mouseDown = false;
Vector2 screenStartSelect, screenEndSelect;
Texture2D texture2d;
void Start(){
texture2d = new Texture2D(3, 3, TextureFormat.ARGB32, false);
// Top Row
texture2d.SetPixel(0, 0, borderColor);
texture2d.SetPixel(1, 0, borderColor);
texture2d.SetPixel(2, 0, borderColor);
// Middle Row
texture2d.SetPixel(0, 1, borderColor);
texture2d.SetPixel(1, 1, innerColor);
texture2d.SetPixel(2, 1, borderColor);
// Bottom Row
texture2d.SetPixel(0, 2, borderColor);
texture2d.SetPixel(1, 2, borderColor);
texture2d.SetPixel(2, 2, borderColor);
texture2d.Apply();
}
// Update is called once per frame
void Update () {
// Mouse button clicked
if(Input.GetMouseButtonDown(0) && !mouseDown){
mouseDown = true;
screenStartSelect = Input.mousePosition;
}
if(mouseDown){
screenEndSelect = Input.mousePosition;
}
// Mouse button released
if(Input.GetMouseButtonUp(0) && mouseDown){
mouseDown = false;
}
}
void OnGUI() {
if (mouseDown) {
GUI.DrawTexture(
new Rect(
screenStartSelect.x,
Screen.height - screenStartSelect.y,
screenEndSelect.x - screenStartSelect.x,
-1 * ((Screen.height - screenStartSelect.y) - (Screen.height - screenEndSelect.y))
),
texture2d
);
}
}
}
结果如下:
答案 0 :(得分:0)
我已经提出了一个有效的解决方案,但不确定这是多么优化:
void OnGUI() {
if (mouseDown) {
var width = (int)(screenEndSelect.x - screenStartSelect.x);
var height = (int)(-1 * ((Screen.height - screenStartSelect.y) - (Screen.height - screenEndSelect.y)));
if((width > 2 || width < -1) && (height > 2 || height < -2)){
texture2d = new Texture2D(Mathf.Abs(width), Mathf.Abs(height), TextureFormat.ARGB32, false);
var fillColorArray = texture2d.GetPixels();
var size = fillColorArray.Length;
var absWidth = Mathf.Abs(width);
for(var i = 0; i < fillColorArray.Length; ++i){
fillColorArray[i] = innerColor;
if(i < absWidth){
fillColorArray[i] = borderColor;
}
if(i > size - absWidth){
fillColorArray[i] = borderColor;
}
if((i % absWidth) == 1){
fillColorArray[i] = borderColor;
}
if((i % absWidth) == absWidth - 1){
fillColorArray[i] = borderColor;
}
}
texture2d.SetPixels(fillColorArray);
texture2d.Apply();
GUI.DrawTexture(
new Rect(
screenStartSelect.x,
Screen.height - screenStartSelect.y,
width,
height
),
texture2d
);
}
}
}
我删除了Start()
方法,现在我在OnGUI()
中创建纹理