C# 第三人称游戏:在当前鼠标位置射击

C# 第三人称游戏:在当前鼠标位置射击,c#,unity3d,line,C#,Unity3d,Line,我是unity的新手,我想做一个小立方体游戏,你可以向敌人射击(见下图)。目前你只能向前射击,你必须移动才能击中敌人。我想让拍摄更加舒适,并在当前鼠标位置拍摄。我只想在x方向拍摄,而不是向上或向下拍摄。但在实现拍摄之前,我想制作一个LineRenderer,指示玩家正在拍摄(如图所示)。因此,我的剧本目前不包括开枪 不幸的是,我不知道如何将鼠标屏幕位置转换为世界坐标,因为我不知道如何为玩家获得正确的深度 在我的脚本中,鼠标的screenToWorld打印出了nonesence,因为我没有正确配置

我是unity的新手,我想做一个小立方体游戏,你可以向敌人射击(见下图)。目前你只能向前射击,你必须移动才能击中敌人。我想让拍摄更加舒适,并在当前鼠标位置拍摄。我只想在x方向拍摄,而不是向上或向下拍摄。但在实现拍摄之前,我想制作一个LineRenderer,指示玩家正在拍摄(如图所示)。因此,我的剧本目前不包括开枪

不幸的是,我不知道如何将鼠标屏幕位置转换为世界坐标,因为我不知道如何为玩家获得正确的深度

在我的脚本中,鼠标的screenToWorld打印出了nonesence,因为我没有正确配置深度(我想)

是否有人知道我如何在当前鼠标位置拍摄,或者让我清楚如何正确设置深度,以便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 m_LineRenderer=null;
矢量3线指向;
私有void Start()
{
线指向=矢量3.0;
m_lineRenderer=GetComponent();
}
无效更新()
{
Vector3鼠标=Input.mousePosition;
mouse.z=transform.position.z;//我想用它来设置播放器的深度
Vector3 mouseOnScreen=Camera.main.ScreenToWorldPoint(鼠标);//屏幕上的鼠标没有打印出我想要的值
linePointing=new Vector3(mouseOnScreen.x,transform.localPosition.y,100);//这里我想将linerenderer的长度设置为100,并使y值保持不变。我只想沿x方向移动。
m_lineRenderer.SetPosition(1,linePointing);//使用此选项,我将lineRenderer的第二个点设置为在子弹飞过时形成一条直线
}
}
我的场景是这样的: 在这个场景中,你可以看到红色立方体,它将成为玩家。红线是线条渲染器,它应该指示玩家正在射击。这一行我想面对屏幕上鼠标的当前位置


嘿,我看到您使用了Input.mousePosition。我要做的是使用GetAxis。这样地 并将其设置为浮点而不是矢量3

float mouseX = Input.GetAxis("Mouse X");

linePointing = new Vector3(mouseX , transform.localPosition.y, 100);

如果在光线投射中使用此选项,则需要制作一个矢量3并将mouseX作为X变量传入。
这将获得MouseX(鼠标在水平视图上的位置)定位并将其设置为mouseX。

我使用的解决方案是将光线从相机投射到鼠标,当光线击中地面时,我得到了我想要的拍摄方向。

使用相机提供的光线查找碰撞。ScreenPointToTay然后无论碰撞发生在何处,让角色朝碰撞方向射击。@Ruzihm好主意。我已经试过了,但在我的例子中,光线投射的命中点和地形总是一样的。你知道为什么吗?@Ruzihm好的,当我发现屏幕上显示的是世界坐标,因此值是这样的。你使用
Input.mousePosition
作为输入?这个问题没有显示您是如何使用我猜
mouse.z=transform.position.z是错误的。作为
z
组件,您需要相机前面的距离,因此可能
mouse.z=transform.z-camera.main.transform.z但总的来说,有点不清楚预期的方向应该是什么样的。。。