【问题标题】:How to make the tank look to the side of the mouse and shoot where the player clicks?如何让坦克看向鼠标的一侧并在玩家点击的地方射击?
【发布时间】:2020-10-10 15:53:19
【问题描述】:

我在第三人称 3D 游戏中有一辆坦克,所以我的相机从上方和侧面看坦克。我需要坦克的炮塔在 y 轴上旋转,以便它始终注视鼠标并在玩家点击的地方射击。问题是我的游戏是 3D 的,而我得到的只是它实际上看着鼠标(就像向上看天空一样)。

这是我现在的代码:

private Vector3 target;
    private Camera cam;

    private void Start()
    {
        cam = Camera.main;
        
    }

    void Update()
    {
        Vector2 mousePos = new Vector2();
        mousePos.x = Input.mousePosition.x;
        mousePos.y = Input.mousePosition.y;
        target = cam.WorldToScreenPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
        transform.LookAt(target);
    }

【问题讨论】:

  • 请确保使用正确的标签。您的代码位于 c# ... unityscript 是/曾经是一种 JavaScript 风格,类似于 Unity 以前使用的自定义语言,现在早已弃用

标签: c# unity3d game-development


【解决方案1】:

你的问题在这里:target = cam.WorldToScreenPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));

您实际需要做的是使用 ScreenPointToRay() 生成从相机射出的射线,然后使用该射线执行 Physics.Raycast() 并从中获取 RaycastHit。然后将目标设置为等于 RaycastHit。

例如:

Ray screenRay;
RaycastHit screenRayHit;

float maxRaycastDistance;

screenRay = cam.ScreenPointToRay(mousePos.x, mousePos.y);

if(Physics.Raycast(screenRay, out screenRayHit, maxRaycastDistance))
{
    target = screenRayHit;
}
else
{
    //just sets the turret to aim at the endpoint of the ray if you aim at nothing
    target = screenRay.GetPoint(maxRaycastDistance);
}

【讨论】:

  • 好吧,我认为我编写的代码应该可以为您提供正确的目标。确保炮塔的枪管沿其 z 轴(或“前”轴)运行,因为 transform.LookAt() 将前向矢量指向目标。基本上,当你在编辑器中点击炮塔时,蓝色箭头应该与炮管平行。
  • 是的,我知道,问题是它正确地位于轴上。
  • 它到底有什么问题?
猜你喜欢
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多