前言
我們都知道兩點能夠連成一直線,要畫兩點是很簡單的,但是兩點之間的所有座標呢? 沒有這些你怎麼畫線 ? 靠,問題瞬間變得複雜起來…。不過好家在,我幫大家寫了一個簡單的算法可以參考,你們就拿去用吧,賺錢了記得分我一點就行。
簡單版 C #
using UnityEngine;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public RawImage img; // 要繪製的圖像
public float x1, y1; // 輸入:點 1
public float x2, y2; // 輸入:點 2
void Start ()
{
Texture2D t = new Texture2D (400, 300); // 與 RawImage 大小相同
float slope = (y2 - y1) / (x2 - x1); // 斜率
for (int i = (int)x1; i < x2; i++) {
int x = i;
int y = Mathf.RoundToInt (slope * (x - x1) + y1);
t.SetPixel (x, y, Color.red);
}
t.Apply ();
img.texture = t;
}
}
強化版 C #
兩點 X 距離很近,線不會斷掉
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
// 要繪製的圖像
public RawImage img;
// 輸入:點 1
public float x1, y1;
// 輸入:點 2
public float x2, y2;
void Start ()
{
Texture2D t = new Texture2D (400, 300); // 與 RawImage 大小相同
float slope = (y2 - y1) / (x2 - x1); // 斜率
int old_y = (int)y1;
if (y1 < y2) {
for (int i = (int)x1; i <= x2; i++) {
int x = i;
int y = Mathf.RoundToInt (slope * (x - x1) + y1);
t.SetPixel (x, y, Color.red);
for (int k = old_y; k < y; k++) {
t.SetPixel (x, k, Color.red);
}
old_y = y;
}
} else {
for (int i = (int)x1; i <= x2; i++) {
int x = i;
int y = Mathf.RoundToInt (slope * (x - x1) + y1);
t.SetPixel (x, y, Color.red);
for (int k = old_y; k > y; k--) {
t.SetPixel (x, k, Color.red);
}
old_y = y;
}
}
t.Apply ();
img.texture = t;
}
}