今天编程的时候遇到一个算法问题,我需要的是做一个数字循环变化的程序代码
例如从0到5每次增加0.02,当数字大小达到5时再每次减小0.02回到0,如此反复进行
从一般思维出发首先这玩意可能需要if条件语句进行限定,于是有以下结果
(伪代码)
float count=0;
if(count >=5){ //大于等于5时开始减少
xxxxxxxxxxxxxxxx
this.count--;
}
else if(count<=0 ){ //小于等于0时开始增加
xxxxxxxxxxxxxx
this.count++;
}
虽然第一眼看上去没什么问题,但是仔细一看会发现这个代码在数字处于0到5之间时就没用了,区间之中的数字既不大于等于5也不小于等于0两个条件均不符合,于是我想到了用一个bool类型解决这个问题,如以下伪代码
bool check=true; //充当增长方向调节装置
float count=0;
if(check){
count ++;
if(count>=5){ //当count变为0时转换数字增长方向
this.chek=false;
}
else{
count --;
if(count<=0){ //当count变为0时转换数字增长方向
this.chek=true;
}
}
}
基本的代码思想已经解决,放到unity的脚本之中具体细化有以下成果
public class MovePlant : MonoBehaviour
{
public float speed = 5.0f;
public float TimeClock = 5.0f;
public bool ChangTime = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
if (this.ChangTime)
{
Vector2 position = transform.position;
position.x -= speed * Time.deltaTime;
transform.position = position;
this.TimeClock-= Time.deltaTime;
if (this.TimeClock < 0)
{
this.ChangTime = false;
}
}
else{
Vector2 position = transform.position;
position.x += speed * Time.deltaTime;
transform.position = position;
this.TimeClock += Time.deltaTime; //此处时间变化尺度用c中的函数(0.02)
if (this.TimeClock >=5)
{
this.ChangTime = true;
}
}
}
}