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

Unity中如何实现物体绕目标旋转、随机平滑变高并可调整旋转半径?

问题分析与解决方案

问题根源

  1. 第一段代码中,每帧执行transform.position = new Vector3(0,Random.Range(0,5f),0)会直接覆盖RotateAround计算出的位置,导致旋转完全失效,且每帧随机高度产生疯狂跳动。
  2. 第二段代码中,ChangePosition直接将物体拉到世界坐标(0,y,0),完全脱离了目标旋转轨道,RotateAround的效果被覆盖,同时高度突变而非平滑过渡。

实现思路

要同时实现绕目标平滑旋转、随机平滑变高、可调整旋转半径,需:

  • 用极坐标计算旋转位置,精准控制半径
  • 维护目标高度/半径,通过插值实现平滑过渡
  • 定时随机更新目标高度/半径,避免突变

完整代码实现

using UnityEngine;

public class RotateAroundTarget : MonoBehaviour
{
    public Transform target;
    public float rotateSpeed = 20f; // 旋转速度(度/秒)
    public float minHeight = 0f;    // 最小高度
    public float maxHeight = 5f;    // 最大高度
    public float minRadius = 2f;    // 最小旋转半径
    public float maxRadius = 5f;    // 最大旋转半径
    public float changeInterval = 3f; // 随机参数更新间隔(秒)

    private float currentAngle;
    private float targetHeight;
    private float currentHeight;
    private float targetRadius;
    private float currentRadius;
    private float smoothSpeed = 2f; // 平滑过渡速度

    void Start()
    {
        // 初始化当前值与目标值
        currentHeight = targetHeight = Random.Range(minHeight, maxHeight);
        currentRadius = targetRadius = Random.Range(minRadius, maxRadius);
        currentAngle = transform.eulerAngles.y;

        // 定时随机更新目标高度和半径
        InvokeRepeating(nameof(RandomizeTargetParams), 0f, changeInterval);
    }

    void Update()
    {
        // 更新旋转角度
        currentAngle += rotateSpeed * Time.deltaTime;

        // 平滑过渡高度和半径
        currentHeight = Mathf.Lerp(currentHeight, targetHeight, smoothSpeed * Time.deltaTime);
        currentRadius = Mathf.Lerp(currentRadius, targetRadius, smoothSpeed * Time.deltaTime);

        // 计算极坐标下的旋转位置
        float x = target.position.x + currentRadius * Mathf.Cos(Mathf.Deg2Rad * currentAngle);
        float z = target.position.z + currentRadius * Mathf.Sin(Mathf.Deg2Rad * currentAngle);
        float y = target.position.y + currentHeight;

        // 应用位置
        transform.position = new Vector3(x, y, z);

        // 让物体始终朝向目标(可选)
        transform.LookAt(target);
    }

    private void RandomizeTargetParams()
    {
        targetHeight = Random.Range(minHeight, maxHeight);
        targetRadius = Random.Range(minRadius, maxRadius);
    }
}

关键说明

  • 用极坐标计算位置替代RotateAround,更精准控制旋转半径,避免位置被直接覆盖的问题
  • 通过Mathf.Lerp实现高度和半径的平滑过渡,消除突变跳动
  • InvokeRepeating仅更新目标参数,不直接修改位置,保证旋转逻辑不受干扰
  • 可通过Inspector调整旋转速度、高度/半径范围、更新间隔等参数,灵活控制效果

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:20:38