Unity 2Dでマウスカーソルの部分に線を描画します。
こちらのサイトを参考にさせていただきました。
空のオブジェクトに Add Componentで「LineRenderer」を追加し、
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
LineRenderer renderer;
Vector3 startPos;
Vector3 pos;
List rendererPositions = new List();
void Start()
{
renderer = gameObject.GetComponent();
// 線の幅
renderer.startWidth = 0.1f;
renderer.endWidth = 0.1f;
//色
Color colorStrat;
ColorUtility.TryParseHtmlString("#" + "FF0000", out colorStrat);
renderer.startColor = colorStrat;
Color colorEnd;
ColorUtility.TryParseHtmlString("#" + "FF0000", out colorEnd);
renderer.endColor = colorEnd;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//タッチ位置取得
Vector3 cameraPosition = Input.mousePosition;
cameraPosition.z = 10.0f;
startPos = Camera.main.ScreenToWorldPoint(cameraPosition);
//ラインの起点設定
renderer.SetPosition(0, startPos);
}
else if (Input.GetMouseButton(0))
{
//タッチ位置取得
Vector3 cameraPosition = Input.mousePosition;
cameraPosition.z = 10.0f;
pos = Camera.main.ScreenToWorldPoint(cameraPosition);
}
else if (Input.GetMouseButtonUp(0))
{
renderer.positionCount = 0;
rendererPositions.Clear();
}
// ラインレンダラーに座標を設定し線を描画
if (!rendererPositions.Contains(pos))
{
rendererPositions.Add(pos);
renderer.positionCount = rendererPositions.Count;
renderer.SetPosition(renderer.positionCount - 1, pos);
}
}
}
線の幅や色の部分を変更することで、だんだん太くなる線や色をグラデーションにすることも可能なようです。