我正在尝试在 Unity 上做我的第一个平台游戏。并且弹丸有问题。我找到了一个教程,如何创建一个移动的射弹,但没有触发 Fire 按钮。可以更改此脚本以触发按钮吗?我试着用 if 语句来实现它,但是弹丸只移动了一个,它不会飞:(
public class projectile : MonoBehaviour
{
public GameObject player;
public GameObject target;
private float playerX;
private float targetX;
private float dist;
private float nextX;
private float baseY;
private float height;
public float speed = 10f;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
target = GameObject.FindGameObjectWithTag("Enemy");
}
void Update()
{
Fire();
}
public static Quaternion LookAtTarget(Vector2 rotation)
{
return Quaternion.Euler(0, 0, Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg);
}
private void Fire()
{
playerX = player.transform.position.x;
targetX = target.transform.position.x;
dist = targetX - playerX;
nextX = Mathf.MoveTowards(transform.position.x, targetX, speed * Time.deltaTime);
baseY = Mathf.Lerp(player.transform.position.y, target.transform.position.y, (nextX - playerX) / dist);
height = 2 * (nextX - playerX) * (nextX - targetX) / (-0.25f * dist * dist);
Vector3 movePosition = new Vector3(nextX, baseY + height, transform.position.z);
transform.rotation = LookAtTarget(movePosition - transform.position);
if (transform.position == target.transform.position)
{
Destroy(gameObject);
}
}
}
Update
方法中的内容每一帧都会发生,因此您需要创建一个手动触发器(bool isFired
)。
想法是当
isFired
为假时,什么也不会发生。
然后,当isFired
变为真时,弹丸开始移动。
您的
Fire
方法实际上使弹丸移动,因此您应该将其重命名为 Move
并且在 Update
中您仅在发射弹丸时调用 Move
。
public class projectile : MonoBehaviour
{
// At the start, the projectile is not fired
bool isFired = false;
void Update()
{
// If the player presses a button, the projectile is fired
if (Input.GetMouseButtonDown(0)) isFired = true;
// Only if the projectile is fired, it should moves
if (isFired) Move();
}
void Move()
{
// Here you have the content of your Fire method
}
}