我試圖制作一款類似于“開鎖游戲”的游戲。但是,我很難在圓圈邊界周圍隨機生成一個點,但不在圓圈內。有關更多詳細資訊,我只想在圓圈的邊界處生成一個游戲物件,而不是在圓圈中的每個位置。請幫助我:< 非常感謝,祝您有美好的一天!p/s:我只是統一引擎和語法的初學者。如果你能給我一些關于如何自學團結的建議,那就太好了。非常感謝
uj5u.com熱心網友回復:
首先,我真的很喜歡Dot Product。我在參考物件周圍隨機放置(在這種情況下transform.position)。randomPos然后在和參考物件之間取方向。用 計算的點積Vector3.Dot()。用點積的結果取randomPos與我們之間的角度。transform.forward使用 Cos 和 Sin 函式計算 x 和 z 值。點積角度總是給出 0 到 180 個值,所以我用乘法給 z 軸賦予了dotProductAngle隨機性(Random.value > 0.5f ? 1f : -1f)。如果你不這樣做,給定的隨機位置將始終在玩家面前。
3D空間
private void SpawnSphereOnEdgeRandomly3D()
{
float radius = 3f;
Vector3 randomPos = Random.insideUnitSphere * radius;
randomPos = transform.position;
randomPos.y = 0f;
Vector3 direction = randomPos - transform.position;
direction.Normalize();
float dotProduct = Vector3.Dot(transform.forward, direction);
float dotProductAngle = Mathf.Acos(dotProduct / transform.forward.magnitude * direction.magnitude);
randomPos.x = Mathf.Cos(dotProductAngle) * radius transform.position.x;
randomPos.z = Mathf.Sin(dotProductAngle * (Random.value > 0.5f ? 1f : -1f)) * radius transform.position.z;
GameObject go = Instantiate(_spherePrefab, randomPos, Quaternion.identity);
go.transform.position = randomPos;
}
3D 示例

二維空間
private void SpawnSphereOnEdgeRandomly2D()
{
float radius = 3f;
Vector3 randomPos = Random.insideUnitSphere * radius;
randomPos = transform.position;
randomPos.y = 0f;
Vector3 direction = randomPos - transform.position;
direction.Normalize();
float dotProduct = Vector3.Dot(transform.forward, direction);
float dotProductAngle = Mathf.Acos(dotProduct / transform.forward.magnitude * direction.magnitude);
randomPos.x = Mathf.Cos(dotProductAngle) * radius transform.position.x;
randomPos.y = Mathf.Sin(dotProductAngle * (Random.value > 0.5f ? 1f : -1f)) * radius transform.position.y;
randomPos.z = transform.position.z;
GameObject go = Instantiate(_spherePrefab, randomPos, Quaternion.identity);
go.transform.position = randomPos;
}
二維示例

希望對你有幫助??
uj5u.com熱心網友回復:
你需要嘗試一些東西并表明你是否被卡住了。我將開始嘗試使用原始語言來理解點旋轉以了解正在發生的事情,例如,在純 c# 中的點旋轉:
// Rotate B around A by angle theta clockwise
private static (double x, double y) Rotate(
(double x, double y) A,
(double x, double y) B,
double theta)
{
double s = Math.Sin(theta);
double c = Math.Cos(theta);
// translate point back to origin:
B.x -= A.x;
B.y -= A.y;
// rotate point clockwise
double xnew = B.x * c - B.y * s;
double ynew = B.x * s B.y * c;
// translate point back:
B.x = xnew A.x;
B.y = ynew A.y;
return B;
}
然后,您可以檢查一些基本的矢量運算及其數學背景,這并不難,并看看使用統一 API 可以做什么: Vector3.Reflect和 Vector3.RotateRowards
當然,你可以想出一些東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/467340.html
