用Unity复现一个简单雨刷器功能

该代码实现了一个简单的Unity3D脚本,用于控制雨刮器的运动。它定义了四个挡位的速度,雨刮器臂的最大角度,以及恢复到0度的默认速度。根据用户输入的数字键,脚本会切换挡位并改变雨刮器的角度,模拟雨刮动作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


using UnityEngine;

public class WiperController : MonoBehaviour
{
    public float[] wiperSpeeds = { 0, 30, 60, 90 }; // 四个挡位的速度
    public float maxAngle = 90f; // 最大角度
    public Transform wiperArmTransform; // 雨刮器臂的Transform
    public float defaultSpeed = 20f; // 默认恢复速度

    private float currentAngle = 0f; // 当前雨刮器臂的角度
    private int currentSpeedIndex = 0; // 当前的挡位
    private float targetAngle = 0f; // 目标角度
    private bool isWiping = false; // 是否在雨刮

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha0))
        {
            // 切换到挡位0,开始慢慢恢复到0度
            currentSpeedIndex = 0;
            targetAngle = 0f;
            isWiping = false;
        }
        else if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            // 切换到挡位1
            currentSpeedIndex = 1;
            isWiping = true;
        }
        else if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            // 切换到挡位2
            currentSpeedIndex = 2;
            isWiping = true;
        }
        else if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            // 切换到挡位3
            currentSpeedIndex = 3;
            isWiping = true;
        }

        // 更新雨刮器角度
        if (isWiping)
        {
            float speed = wiperSpeeds[currentSpeedIndex];
            float targetAngleDelta = speed * Time.deltaTime;
            float angleDelta = Mathf.Clamp(targetAngle - currentAngle, -targetAngleDelta, targetAngleDelta);
            currentAngle += angleDelta;

            if (Mathf.Abs(currentAngle - targetAngle) < 0.1f)
            {
                targetAngle = (targetAngle == 0f) ? maxAngle : 0f;
            }

            wiperArmTransform.localRotation = Quaternion.Euler(new Vector3(0f, 0f, currentAngle));
        }
        else if (Mathf.Abs(currentAngle) > 0.1f)
        {
            // 如果正在恢复到0度,则按默认速度恢复
            float delta = Mathf.Sign(-currentAngle) * defaultSpeed * Time.deltaTime;
            currentAngle += delta;

            if (Mathf.Abs(currentAngle) < Mathf.Abs(delta))
            {
                currentAngle = 0f;
            }

            wiperArmTransform.localRotation = Quaternion.Euler(new Vector3(0f, 0f, currentAngle));
        }
    }



}

只是简单的从0到90度反复刷,没有写特别复杂的功能

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值