C# 移向鼠标单击

C# 移向鼠标单击,c#,unity3d,C#,Unity3d,我尝试在单击时使用速度将对象移向鼠标,但当我单击时,对象通常会朝不同的方向移动。我基本上是从另一个项目中复制代码的,在那个项目中它可以工作。唯一的区别是,在另一个项目中,我使用AddForce而不是设置速度。是什么导致它这样做的 using UnityEngine; using System.Collections; public class ShootBall : MonoBehaviour { public float shootDelay = 0.03f; public

我尝试在单击时使用速度将对象移向鼠标,但当我单击时,对象通常会朝不同的方向移动。我基本上是从另一个项目中复制代码的,在那个项目中它可以工作。唯一的区别是,在另一个项目中,我使用
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);
        }
    }
}
使用UnityEngine;
使用系统集合;
公共课射击:单一行为{
公共交通延误=0.03f;
公共游戏对象[]球;
布尔·哈肖特=假;
Vector3单击位置=Vector3.0;
//每帧调用一次更新
无效更新(){
if(Input.GetMouseButtonUp(0)&&!hasShot){
hasShot=正确;
Vector3点=Camera.main.ScreenToWorldPoint(Input.mousePosition);
矢量2方向=点-变换位置;
开始例行程序(拍摄(方向));
}
}
IEnumerator拍摄(矢量2方向){
foreach(游戏对象球在球中){
浮动速度=ball.GetComponent().速度;
ball.GetComponent().rb.velocity=direction.normalized*速度;
产生返回新的WaitForSeconds(shootDelay);
}
}
}

尝试反转方向向量,如下所示:

Vector2 direction = transform.position - point;
或在此:

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

这两种方法都不能解决问题。请尝试使用来确定
方向是否正确。我发现,我使用的是管理器对象的
变换。位置
,而不是实际球的
球[0]。变换。位置