发射弹丸但方向错误 - 2D 游戏

Shooting a projectile but goes in wrong direction - 2D game

我正在尝试制作一个简单的游戏,当用户触摸屏幕时,我会发射弹丸,我首先会产生 8 个弹丸(精灵),当用户触摸屏幕时,我希望顶部的弹丸飞入触摸方向。我能够做到这一点;但是,每次我射击时,弹丸的方向都是错误的,这里有一张图片可以说明这个问题。

显然图像还在,但物体会继续飞行,直到它离开屏幕然后被摧毁。

这是处理此问题的代码片段

GameplayController.cs

if (Input.GetMouseButtonDown(0))
    {
        Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
        position = Camera.main.ScreenToWorldPoint(position);

        GameObject target;
        target = new GameObject();
        target.transform.position = position;


        Arrow comp = currentArrows[0].GetComponent<Arrow>();
        comp.setTarget(target.transform);
        comp.GetComponent<Arrow>().arrowSpeed = 12;
        comp.GetComponent<Arrow>().shoot = true;
        currentArrows.RemoveAt(0);
        Destroy(target);
    }

我知道我在这里得到的是鼠标输入,而不是 phone 触摸,这对我来说很好,稍后我会将其转换为触摸输入。

Arrow.cs

public bool shoot = false;
public float arrowSpeed = 0.0f;
public Vector3 myDir;
public float speed = 30.0f;
private Transform target;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if(shoot)
    {
        transform.position += transform.right * arrowSpeed * Time.deltaTime;
    }

}


public void setTarget(Transform targetTransform)
{
    this.target = targetTransform;
    Vector3 vectorToTarget = target.position - transform.position;
    float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
    Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
    transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * speed);
}

private void OnBecameInvisible()
{
    print("Disappeared");
    Destroy(gameObject);
    Gameplay.instance.isShooting = false;
}

Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);

我认为你的问题是你通过点击获得的是屏幕坐标,而不是世界坐标,这实际上是两个不同的东西。为了正确地引导你的射弹,你需要像完成的那样将你的屏幕坐标转换为世界坐标 here

接下来是如何移动射弹:

transform.position += transform.right * arrowSpeed * Time.deltaTime;

您正在将射弹向右移动,然后以某种方式旋转它。也许你应该尝试用 Vector3.Lerp, which will be easier and rotate it with Transform.LookAt.

移动它