【问题标题】:Third Person Game: Shooting at current mouse position第三人称游戏:在当前鼠标位置射击
【发布时间】: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;,但总的来说,有点不清楚预期方向应该是什么样子......

标签: c# unity3d line


【解决方案1】:

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

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

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

如果你在 Raycast 中使用它,你需要创建一个 Vector3 并将 mouseX 作为 X 变量传入。 这将获取 MouseX(鼠标在水平视图上的位置)位置并将其设置为 mouseX。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 2021-07-14
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多