Unity 兩點之間畫線

前言

我們都知道兩點能夠連成一直線,要畫兩點是很簡單的,但是兩點之間的所有座標呢? 沒有這些你怎麼畫線 ? 靠,問題瞬間變得複雜起來…。不過好家在,我幫大家寫了一個簡單的算法可以參考,你們就拿去用吧,賺錢了記得分我一點就行。


簡單版 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;
    }
}


結果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值