【发布时间】:2020-10-15 19:11:39
【问题描述】:
我是 Unity 新手,想制作一个可以射击敌人的小方块游戏(见下图)。目前你只能向前射击,你必须移动才能击中敌人。我想让拍摄更舒适,在当前鼠标位置拍摄。我只想在 x 方向上拍摄,而不是向上或向下。但在实施拍摄之前,我想制作一个 LineRenderer 来指示玩家正在拍摄(如图所示)。因此,我的脚本暂时不包括射击子弹。
不幸的是,我不知道如何将 mouseOnScreen Position 转换为世界坐标,因为我不知道如何为玩家获取正确的深度。
在我的脚本中,鼠标的 screenToWorld 打印出无意义的,因为我没有正确配置深度(我认为)。
有人知道我如何在当前鼠标位置进行拍摄,或者让我了解如何正确设置深度,以便 screentoWorld 打印出正确/想要的值。
这是我写的代码:
public class ShootingAtScript : MonoBehaviour
{
private LineRenderer m_lineRenderer = null;
Vector3 linePointing;
private void Start()
{
linePointing = Vector3.zero;
m_lineRenderer = GetComponent<LineRenderer>();
}
void Update()
{
Vector3 mouse = Input.mousePosition;
mouse.z = transform.position.z; //With this I want to set the depth of the player
Vector3 mouseOnScreen = Camera.main.ScreenToWorldPoint(mouse); //Mouse on screen doesnt print out the values I want
linePointing = new Vector3(mouseOnScreen.x , transform.localPosition.y, 100); //Here I want to set the length of the linerenderer to 100 and make the y value stay were it is. I just want to move in the x direction.
m_lineRenderer.SetPosition(1, linePointing); //With this I set the second point of my linerenderer to make a straight line were the bullet would be flying
}
}
我的场景是这样的: 在这个场景中,您可以看到将成为玩家的红色立方体。红线是 lineRenderer,应该表明玩家正在射击。而这条线我要面向屏幕上当前鼠标的位置。
【问题讨论】:
-
使用
Camera.ScreenPointToTay给出的射线找到一个碰撞,然后无论碰撞在哪里,让角色朝着那个碰撞射击。 -
@Ruzihm 好主意。我已经尝试过了,但就我而言,光线投射的命中点和例如地形总是相同的。你知道为什么吗?
-
@Ruzihm 好的,所以我发现 ScreenToRay 正在打印出协调的世界,因此值是这样的。
-
您使用
Input.mousePosition作为输入?该问题未显示您如何使用ScreenPointToRay -
我猜
mouse.z = transform.position.z;是错误的。作为z组件,您需要相机前面的距离,所以可能是mouse.z = transform.z - Camera.main.transform.z;,但总的来说,有点不清楚预期方向应该是什么样子......