You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity3D中使用InvokeRepeating随机沿X/Z轴缩放平面的实现疑问

Unity Plane 随机轴旋转+缩放实现

核心逻辑

每次定时触发时,先随机选定世界空间的X/Z轴,将Plane绕Y轴旋转至对应朝向,再随机对该轴方向进行拉伸或缩小操作,用InvokeRepeating来定时执行这套逻辑即可。

完整代码实现

using UnityEngine;

public class PlaneScaler : MonoBehaviour
{
    // 定时触发间隔(秒),可在Inspector面板调整
    public float repeatInterval = 2f;
    // 每次缩放的幅度
    public float scaleStep = 0.5f;
    // 缩放的最小/最大值,防止过度拉伸或缩小
    public float minScale = 0.5f;
    public float maxScale = 5f;

    private void Start()
    {
        // 启动定时任务:1秒后首次执行,之后每隔repeatInterval秒执行一次
        InvokeRepeating(nameof(RandomRotateAndScale), 1f, repeatInterval);
    }

    private void RandomRotateAndScale()
    {
        // 随机选择目标轴:0代表X轴,1代表Z轴
        int axisChoice = Random.Range(0, 2);
        Vector3 targetRotation = Vector3.zero;

        // 根据选中的轴设置旋转角度(绕Y轴旋转,让Plane局部轴对齐目标世界轴)
        if (axisChoice == 0)
        {
            // 对齐世界X轴,Y轴旋转0度
            targetRotation = new Vector3(0, 0, 0);
        }
        else
        {
            // 对齐世界Z轴,Y轴旋转90度
            targetRotation = new Vector3(0, 90, 0);
        }

        // 直接设置旋转(新手用这种方式最直观,需要平滑旋转可替换为Quaternion.Lerp)
        transform.rotation = Quaternion.Euler(targetRotation);

        // 随机选择缩放方向:0缩小,1拉伸
        int scaleDirection = Random.Range(0, 2);
        Vector3 newScale = transform.localScale;

        // 根据选定轴调整缩放值,同时限制在设定范围内
        if (axisChoice == 0)
        {
            newScale.x = scaleDirection == 1 ? 
                Mathf.Min(newScale.x + scaleStep, maxScale) : 
                Mathf.Max(newScale.x - scaleStep, minScale);
        }
        else
        {
            newScale.z = scaleDirection == 1 ? 
                Mathf.Min(newScale.z + scaleStep, maxScale) : 
                Mathf.Max(newScale.z - scaleStep, minScale);
        }

        // 应用新的缩放
        transform.localScale = newScale;
    }
}

关键细节说明

  • 旋转逻辑:Plane默认处于XZ平面,绕Y轴旋转90度后,其局部X轴会对齐世界Z轴,此时缩放局部X轴就等同于沿世界Z轴拉伸。
  • 缩放限制:用Mathf.Min/Max锁定缩放范围,避免Plane缩到消失或过度拉伸影响视觉效果。
  • InvokeRepeating参数:第一个参数是要执行的方法名,第二个是首次执行的延迟时间,第三个是每次执行的间隔时长。

使用步骤

  1. 创建3D Object > Plane,将此脚本拖到Plane对象上。
  2. 在Inspector面板调整repeatInterval(触发间隔)、scaleStep(每次缩放幅度)、minScale/maxScale(缩放范围)。
  3. 运行游戏,Plane会定时随机旋转到X/Z轴方向,然后自动进行拉伸或缩小操作。

内容的提问来源于stack exchange,提问作者AmIt PagarIa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:05:29