2017-04-10 171 views
0

我尝试使用速度单击时向我的鼠标移动对象,但当单击对象时通常会沿不同方向移动。我基本上从另一个项目复制代码,并在该项目中工作。唯一的区别是在另一个项目中,而不是设置速度,我使用AddForce。是什么导致它做它正在做的事情?移动鼠标点击

using UnityEngine; 
using System.Collections; 

public class ShootBall : MonoBehaviour { 

    public float shootDelay = 0.03f; 
    public GameObject[] balls; 
    bool hasShot = false; 

    Vector3 clickPosition = Vector3.zero; 

    // Update is called once per frame 
    void Update() { 
     if (Input.GetMouseButtonUp(0) && !hasShot) { 
      hasShot = true; 
      Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition); 
      Vector2 direction = point - transform.position; 
      StartCoroutine(Shoot(direction)); 
     } 
    } 

    IEnumerator Shoot(Vector2 direction) { 
     foreach (GameObject ball in balls) { 
      float speed = ball.GetComponent<Ball>().speed; 
      ball.GetComponent<Ball>().rb.velocity = direction.normalized * speed; 
      yield return new WaitForSeconds(shootDelay); 
     } 
    } 
} 

回答

0

尝试扭转的方向向量,无论是在这里:

Vector2 direction = transform.position - point; 

或者在这里:

ball.GetComponent<Ball>().rb.velocity = -direction.normalized * speed; 
+0

那些都解决它。 –

+0

尝试使用[Gizmos.DrawLine](https://docs.unity3d.com/ScriptReference/Gizmos.DrawLine.html)来确定“方向”是否正确。 – Iggy

+0

想通了,我使用的是管理对象的'transform.position'而不是实际球的'ball [0] .transform.postion'。 –