Unity模拟传送带
1.模型搭建
2.添加部件
2.1添加触发器
为传送带添加触发器,使得当物体停留在传送带时能一直向前移动。
2.2 设置空物体作为传送带终点位置
2.3为传送带设置开关和速度加速装置
本展示的传送带开关装置是通过空格键进行控制,加速装置通过数字1控制
3. 源代码
public GameObject belt;
public Transform endpoint;//获取终点位置
public int currentSpeed;//当前速度
public int maxSpeed;//传送带最大速度
public bool belton=false;//判断传送带是否开启
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
PowerSwitch();
}
else if (Input.GetKeyDown(KeyCode.Alpha1))
{
ChangeSpeed();
}
}
void ChangeSpeed()
{
if(currentSpeed>=maxSpeed)
{
currentSpeed = 0;
}
else
{
currentSpeed++;
}
}
void PowerSwitch()
{
if(belton)
{
belton = false;
}
else
{
belton = true;
}
}
private void OnTriggerStay(Collider collider)
{
if(belton)
{
collider.transform.position = Vector3.MoveTowards(collider.transform.position, endpoint.position, currentSpeed * Time.deltaTime);
}
}