【问题标题】:How to find direction and calculate end point of a raycast Unity2D如何找到方向并计算光线投射 Unity2D 的终点
【发布时间】:2021-08-19 12:32:54
【问题描述】:

我正在尝试在 Unity 中制作一把枪,它可以用 Line 发射 Raycast。 (在 2d 中)我使用玩家位置作为原点,鼠标位置作为方向。这在有碰撞检测时非常有效,但是当没有碰撞时,我必须手动找到方向并计算终点,因为如果玩家错过了射门,我仍然希望线渲染。这是我找到这个端点的代码:

        //finding the position of Mouse in worldspace
    Vector3 mousePos = CameraController.mouseToWorld(Input.mousePosition);
    mousePos.z = 0;

    //Calculating whether or not the raycast is a hit
    RaycastHit2D Ray = Physics2D.Raycast(Player.transform.position,mousePos,distance);
    if(Ray.collider != null)
    {
        PassTheHit(Ray, Ray.collider.gameObject.name);

        point = Ray.point;
    }
    else
    {
        //Calculating the farthest point on the line. this does not work.
        point = (transform.position - mousePos).normalized;
        point *= -1 * (distance / 2);
        point.z = 0f;
    }

特别注意 else{} 语句。找到该点的计算不起作用。它太长了,而且没有朝正确的方向射击。

非常感谢任何帮助。

【问题讨论】:

    标签: c# unity3d math


    【解决方案1】:

    无论哪种方式,您都错误地使用了Physics2D.Raycast。它期望一个

    • 开始位置
    • 和一个方向

    你正在第二个位置传球。

    你更想做的是使用方向

    Vector2 mousePos = CameraController.mouseToWorld(Input.mousePosition);
    
    Vector2 direction = ((Vector2)(mousePos - transform.position)).normalized;
    

    你可以同时使用它

    RaycastHit2D Ray = Physics2D.Raycast(Player.transform.position, /*here*/ direction, distance);
    if(Ray.collider != null)
    {
        PassTheHit(Ray, Ray.collider.gameObject.name);
    
        point = Ray.point;
    }
    else
    {
        point = transform.position + /*and here*/ direction * distance;
    }
    

    旁注:避免将RaycastHit2D 命名为Ray,因为有一种类型称为Ray,因此会产生误导;)

    【讨论】:

    • 谢谢@derHugo!那行得通! :D 但是有一个问题,这条线朝相反的方向走。通过将方向乘以 -1 来修复它。
    • @RylanYancey 是的,我看到了我的错误并且已经更新了代码;)向量总是去endpoint - startpoint;)
    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2021-09-07
    • 1970-01-01
    • 2018-08-07
    • 2019-03-17
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    相关资源
    最近更新 更多