代码之家  ›  专栏  ›  技术社区  ›  Muhand Jumah

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

  •  0
  • Muhand Jumah  · 技术社区  · 7 年前

    我试图做一个简单的游戏,当用户触摸屏幕时,我拍摄一个投射物,我首先生成8个投射物(精灵),当用户触摸屏幕时,我希望顶部的投射物沿着触摸方向飞行。我能够做到这一点;然而,每次我拍摄时,投射物都会朝着错误的方向移动,下面的图片将说明这个问题。

    Projectile

    下面是处理此问题的代码段

    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);
        }
    

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

    箭反恐精英

    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;
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   vmchar    7 年前

    Vector3位置=新Vector3(Input.mousePosition.x,Input.mousePosition.y,0);

    我认为你的问题是你得到了 屏幕 here .

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

    Vector3.Lerp Transform.LookAt