我真的不知道這個問題的標題應該是什么樣子,bcs這個問題更復雜。這里我上傳了2張圖片。
在這里,我使用從 0 到行長的位置創建了板,然后我添加了 linerenderer 以從第一個觸摸位置到最后一個觸摸位置畫一條線,一切正常

所以我的問題是如何從起點到最后一點畫一條線,但是如果從起點的線不在 45 度角,則將其設定為 45 角,在 x 和 y 之間以及從起點。Fe如果我有上圖這樣的情況,我想像下圖那樣轉換它。
它應該看起來像這樣,只有線條應該能夠水平、垂直和對角線(180,90 和 45 度)

因此,如果該線未在任何此方向上繪制,請將其移至最近的方向。
uj5u.com熱心網友回復:
在不了解您的專案的更多資訊的情況下,您可以使用類似的方法將您的輸入映射到可用的方向上
private readonly Vector2[] _availableDirections =
{
Vector2.up,
Vector2.right,
Vector2.down,
Vector2.left,
new Vector2.one,
-new Vector2.one,
new Vector2(1, -1),
new Vector2(-1, 1)
};
private Vector2 MapToClosestDirection(Vector2 startPoint, Vector2 endPoint)
{
// get the current input direction
var currentDirection = (endPoint - startPoint);
// Find the available direction for which the angle is the smallest
var smallestAngle = float.MaxValue;
var direction = currentDirection;
foreach (var availableDirection in _availableDirections)
{
var currentAngle = Vector2.Angle(currentDirection, availableDirection);
if (currentAngle < smallestAngle)
{
direction = availableDirection;
smallestAngle = currentAngle;
}
}
// then project your input onto this direction
var mappedDirection = (Vector2)Vector3.Project(currentDirection, direction);
return startPoint mappedDirection;
}
這可能看起來像
[SerializeField]
private LineRenderer _line;
[SerializeField]
private Camera _camera;
private readonly Vector2[] _availableDirections =
{
Vector2.up,
Vector2.right,
Vector2.down,
Vector2.left,
new Vector2.one,
-new Vector2.one,
new Vector2(1, -1),
new Vector2(-1, 1)
};
private Vector2 _startPoint;
private void Awake()
{
if (!_camera) _camera = Camera.main;
_line.positionCount = 2;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
_line.gameObject.SetActive(true);
_startPoint = _camera.ScreenToWorldPoint(Input.mousePosition);
_line.SetPosition(0, _startPoint);
}
if (Input.GetMouseButton(0))
{
_line.SetPosition(1, MapToClosestDirection(_startPoint, _camera.ScreenToWorldPoint(Input.mousePosition)));
}
if (Input.GetMouseButtonUp(0))
{
_line.gameObject.SetActive(false);
}
}
private Vector2 MapToClosestDirection(Vector2 startPoint, Vector2 endPoint)
{
var currentDirection = (endPoint - startPoint);
var smallestAngle = float.MaxValue;
var direction = currentDirection;
foreach (var availableDirection in _availableDirections)
{
var currentAngle = Vector2.Angle(currentDirection, availableDirection);
if (currentAngle < smallestAngle)
{
direction = availableDirection;
smallestAngle = currentAngle;
}
}
var mappedDirection = (Vector2)Vector3.Project(currentDirection, direction);
return startPoint mappedDirection;
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432332.html
標籤:unity3d
上一篇:C#錯誤“CS0116:命名空間不能直接包含欄位或方法等成員”
下一篇:繼續執行“GetKeyUp”命令
