我正试图让我的敌舰模拟实际的太空飞船。因此,船只向前加速,但随着时间的推移,其移动方向将如所附图像所示。这需要面对一个随机的方向,但必须平稳过渡到下一个方向,以阻止这种抖动影响我目前使用的方法。
我目前正在尝试执行已显示的代码,但这会使敌人在每次旋转及其不平滑之间闪烁。
public float directionChangeTimer = 5f;
public float accelerateSpeed;
public void addRandomDirection()
{
float randomAngleAdd = Random.Range(-5f, 5f);
transform.Rotate(0, 0, randomAngleAdd);
}
public void Update()
{
//Add our Functions
addRandomDirection();
}
答案 0 :(得分:0)
当前,您在-5
和5
度之间旋转每帧。
如果您想使它更平滑,可以使用Coroutine之类的
public float directionChangeTimer = 5f;
public float anglesPerSecond = 1f;
public float accelerateSpeed;
private void Start()
{
StartCoroutine(RandomRotations);
}
private void IEnumerator RandomRotations()
{
while(true)
{
// wait for directionChangeTimer seconds
yield return new WaitForSeconds(directionChangeTimer);
// get currentRotation
var startRot = transform.rotation;
// pick the next random angle
var randomAngleAdd = Random.Range(-5f, 5f);
// store already rotated angle
var alreadyRotated = 0f;
// over time add the rotation
do
{
// prevent overshooting
var addRotation = Mathf.Min(Mathf.Abs(randomAngleAdd) - alreadyRotated, Time.deltaTime * anglesPerSecond);
// rotate a bit in the given direction
transform.Rotate(0, 0, addRotation * Mathf.Sign(randomAngleAdd));
alreadyRotated += addRotation;
yield return null;
}
while(alreadyRotated < Mathf.Abs(randomAngleAdd));
}
}