我正在尝试使用单击时使用速度将对象移向鼠标,但是当我单击该对象时,通常会朝不同的方向移动。我基本上从另一个项目中复制了代码,并在该项目中工作。唯一的区别是,在另一个项目而不是设置速度,我使用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 :(得分:0)
尝试在此处反转方向向量:
Vector2 direction = transform.position - point;
或者在这里:
ball.GetComponent<Ball>().rb.velocity = -direction.normalized * speed;