我的总体目标是有一个脚本,它不断地沿 y 轴生成一个对象,直到一段音频停止播放。所讨论的物体是“星域”,它们是创造外太空效果的恒星群。这可以很容易地完成,我已经知道如何使用恒定速度来做到这一点。对我来说最难的部分是用一个越来越快的对象来生成这些对象。
为了详细说明这一点,使用下面的脚本有一个越来越快的火箭,它将我设置的恒定速度 (10) 与 Vector3 的运动相乘。正如您在代码中看到的那样,它的加速度为 0.25。这个想法是火箭继续飞行,直到音频结束并且星星停止产卵并且游戏结束。火箭逐渐变得越来越快,所以我不能硬编码它。
下面是我的火箭和星星生成脚本的代码。
这只是解决问题的一种方法,我花了很长时间尝试不同的东西,但似乎没有任何效果。我觉得有一种更简单的方法可以解决这个问题。
星星生成代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StarSpawn : MonoBehaviour {
// Use this for initialization
public Transform Object;
AudioSource Music;
float MusicClipLength;
float distance;
void Start()
{
Music = GetComponent<AudioSource>();
AudioClip MusicClip;
MusicClip = Music.clip;
MusicClipLength = Music.clip.length; //time
distance = ((((0.5f * 0.25f) * (MusicClipLength * MusicClipLength)))); //distance
float RoundedDistance = (float)Mathf.Floor(distance); //rounding
for (int i = 0; i <= RoundedDistance; i++) //generation loop
{
Instantiate(Object, new Vector3(0, i * 1750.0f, 500),
Quaternion.Euler(-90, 0, 90));
}
}
}
火箭代码(其中一些无关紧要)
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerController : MonoBehaviour
{
public bool Launch = false;
private Rigidbody rb;
public int Speed;
void Start()
{
rb = GetComponent<Rigidbody>();
}
public void LaunchStart()
{
Launch = true;
}
void FixedUpdate()
{
float altitude = (rb.position.y);
if (Launch == true)
{
float moveHorizontal = CrossPlatformInputManager.GetAxis("Horizontal");
Vector3 movement = new Vector3(moveHorizontal, 0.25f, 0.0f);
if (altitude > 0)
{
rb.AddForce(movement * Speed);
}
}
}
}
例如,0.25 是一切的加速度,10 是设定的公共(public)速度。
我意识到这是一个很大的问题,所以即使有人认识到解决问题的更简单方法,我也会非常感谢任何建议。
编辑
我的实际问题是星星过度生成,太多了。所以当音频结束时,还有很多星星。
最佳答案
在这里使用协程可能是一个不错的选择。这样,您就可以使用火箭的速度来确定生成恒星之间的时间延迟:
float totaltime;
void Start()
{
Music = GetComponent<AudioSource>();
AudioClip MusicClip;
MusicClip = Music.clip;
MusicClipLength = Music.clip.length; //time
distance = ((((0.5f * 0.25f) * (MusicClipLength * MusicClipLength)))); //distance
float RoundedDistance = (float)Mathf.Floor(distance); //rounding
StartCoroutine(Spawner());
}
void IEnumerator Spawner()
{
totaltime += Time.deltaTime;
while (totaltime < MusicClipLength)
{
Instantiate(Object, new Vector3(0, i * 1750.0f, 500), Quaternion.Euler(-90, 0, 90));
yield return new WaitForSeconds(rocketspeedFactor); // you should mess around with this value to get the spawning frequency correct.
// would be good to retrieve the speed from the rocket and multiple by some factor
}
}
关于c# - 如何为音频剪辑的长度实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51788348/