基础算法问题 unity脚本移动平台,解决数字循环变化问题

今天编程的时候遇到一个算法问题,我需要的是做一个数字循环变化的程序代码

例如从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;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值