线条渲染器和项目符号之间的拍摄方向不同

问题描述

我正在实施我的第一个第三人称游戏。在这个游戏中,我想用鼠标的方向射击。因此,我将光线从相机投射到地面。为了使拍摄效果更好,我在播放器和当前鼠标位置之间划了一条线(请参见屏幕截图)。

如果玩家按下射击按钮,则子弹应沿着线条渲染器的方向生成并射击。

不幸的是,子弹没有朝着鼠标的方向飞行,我不确定为什么吗?

两个脚本:线条渲染器,项目符号生成和射击都在同一个游戏对象上。

当前代码

Line Renderer:

void Update()
{
    Vector3 pos = new Vector3(200,200,0);
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    

    if (Physics.Raycast(ray,out hit,100)) 
    {


        linePointing = new Vector3(hit.point.x,hit.point.y,hit.point.z); // really unnecessary but I want the line Pointing as my hit point

        linePointing.y = gameObject.transform.position.y;
        Vector3 localCord = gameObject.transform.InverseTransformPoint(linePointing);



        float angle = Mathf.atan(localCord.x / localCord.z) * Mathf.Rad2Deg;

        //This is just so the player cant shoot in every direction
        if (Mathf.Abs(angle) < 80 && localCord.z > 0)
        {
            m_lineRenderer.SetPosition(1,localCord);
            m_lineRenderer.SetPosition(2,localCord * 100);
        }


    }

}

子弹生成(也在更新中)

    GameObject bullet = Instantiate(bulletPrefab);
    bullet.transform.parent = gameObject.transform.parent;

    Physics.IgnoreCollision(bullet.GetComponent<Collider>(),bulletSpawn.parent.GetComponent<Collider>());

    bullet.transform.position = bulletSpawn.position;

    Vector3 rotation = bullet.transform.rotation.eulerAngles;

    bullet.transform.rotation = Quaternion.Euler(rotation.x,transform.eulerAngles.y,rotation.z);
    bullet.GetComponent<Rigidbody>().AddForce(getShootingDirection().normalized * bulletSpeed,ForceMode.Impulse);

    //Change parent,so the player movement doesnt affect the bullet
    bullet.transform.parent = null;

获取射击方向-方法方法与行渲染器的方法相同,但我想将其分开

 private Vector3 getShootingDirection()
{
    Vector3 linePointing = Vector3.zero;
    Vector3 localCord = Vector3.zero;
    Vector3 pos = new Vector3(200,0);
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray,100))
    {
        linePointing = new Vector3(hit.point.x,hit.point.z)
        {
            y = hit.point.y + 0.5f
        };

        localCord = gameObject.transform.InverseTransformPoint(linePointing);


    }
    return localCord;

}

线条渲染器的图片

enter image description here

解决方法

RigidbodyAddforce在世界坐标中添加力,我认为您正在以局部坐标添加力。您可以检查出来。