C# 类雷击游戏中的问题实例化块
我试图用光线投射实例化像Minecraft这样的块。它可以工作,但是如果我单击旋转方向与(0,0,0)不同的块,我的块将在我单击的块的相同位置生成 我的代码:C# 类雷击游戏中的问题实例化块,c#,unity3d,C#,Unity3d,我试图用光线投射实例化像Minecraft这样的块。它可以工作,但是如果我单击旋转方向与(0,0,0)不同的块,我的块将在我单击的块的相同位置生成 我的代码: Vector3 SnappedPosition(Vector3 pointToSnap, Vector3 blockCenterPosition) { Vector3 relativePosition = pointToSnap - blockCenterPosition; Debug.Log("pointTo
Vector3 SnappedPosition(Vector3 pointToSnap, Vector3 blockCenterPosition)
{
Vector3 relativePosition = pointToSnap - blockCenterPosition;
Debug.Log("pointToSnap ="+pointToSnap);
Debug.Log("blockCenterPosition =" + blockCenterPosition);
Debug.Log("relativePosition = pointToSnap - blockCenterPosition =" + relativePosition);
if (relativePosition.x == 0.5) { Debug.Log("Vector.right"); return blockCenterPosition + Vector3.right; }
if (relativePosition.x == -0.5){ Debug.Log("Vector.left"); return blockCenterPosition + Vector3.left; }
if (relativePosition.y == 0.5) { Debug.Log("Vector.up"); return blockCenterPosition + Vector3.up; }
if (relativePosition.y == -0.5) { Debug.Log("Vector.down"); return blockCenterPosition + Vector3.down; }
if (relativePosition.z == 0.5) { Debug.Log("Vector.forwad"); return blockCenterPosition + Vector3.forward; }
if (relativePosition.z == -0.5) { Debug.Log("Vector.back"); return blockCenterPosition + Vector3.back; }
Debug.Log("Vector3.zero");
return Vector3.zero; // error (should not occur)
}
void Start()
{
hand = dust;
// to avoid collision with player camera during raycast
playerMask = ~LayerMask.GetMask("Player"); // everything except the player mask
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse1)) // right click --> place block
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
Vector3 pointToSnap = hit.point;
Vector3 blockCenterPosition = hit.collider.transform.localPosition;
Vector3 instantiatePosition = SnappedPosition(pointToSnap, blockCenterPosition);
Debug.Log("instatiatePosition = blockCenterPosition + Vector " + instantiatePosition);
Instantiate(hand, instantiatePosition, Quaternion.identity);
}
}
}
调试:
放置2个街区。
运行时不更改旋转:工作
- pointToSnap=(0.0,-0.5,0.0)
- blockCenterPosition=(0.0,0.0,0.0)
- 相对位置=点捕捉-区块中心位置=(0.0,0.5,0.0)
- 向量机
- instatiatePosition=区块中心位置+矢量(矢量向上)= (0.0,1.0,0.0);李>
- pointToSnap=(0.2,-0.5,0.0)
- blockCenterPosition=(0.0,0.0,0.0)
- 相对位置=点捕捉-区块中心位置=(0.2,0.5,0.0)
- Vector.zero(如果relativePosition.y为0.5,为什么?正确答案是Vector.up)从不使用
直接比较==
浮点值。由于
可能是5*0.2f/10f
或0.9999999
,因此检查1.0000000001
将失败 因此,您总是希望检查它是否位于某个范围内,例如==1f
基本上等于做if(Mathf.Abs(a - b) <= threshold)
if(Mathf.Abs(a - b) <= Mathf.Epsilon)
if(Mathf.Abs(a-b)
if(Mathf.Abs(a - b) <= Mathf.Epsilon)