Unity 绕物体旋转两种方式
前言
项目上遇到一个要绕物体旋转的问题,还要可以动态修改旋转中心和旋转半径。
第一种方式
使用Unity自带的API RotateAround
有两个问题
- 物体移动的时候无法准确跟随
- 无法修改圆的半径

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemScript : MonoBehaviour
{
//中心点
public Transform center;
//转动速度
public float rotationSpeed=10;
void Update() {
//跟随center转圈圈
this.transform.RotateAround(center.position, Vector3.forward, Time.deltaTime * rotationSpeed);
}
}
第二种方式
可以动态修改中心点的位置和旋转半径
已知圆心坐标:(x0,y0)
半径:r
角度:a
则圆上任一点为:(x1,y1)
则
x1 = x0 + r * cos( a )
y1 = y0 + r * sin( a )
作者:初同学
链接: https://www.jianshu.com/p/ba69d991f1af
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemScript : MonoBehaviour
{
//转动速度
public float speed = 1;
//转动的位置
public float progress = 0;
//中心点
public Transform center;
//半径
public float radius = 3;
void Update() {
progress += Time.deltaTime * speed;
if (progress>=360)
{
progress -= 360;
}
float x1 = center.position.x + radius * Mathf.Cos(progress);
float y1 = center.position.y + radius * Mathf.Sin(progress);
this.transform.position = new Vector3(x1, y1);
}
}
随机环绕

//中心点
public Transform center;
//旋转速度
public float rotationSpeed=5;
//半径
public float rotationRadius = 2;
//转动的位置
public float progress = 0;
public float randAng = 0;
public Vector3 randZhou;
private void Start()
{
randAng= Random.Range(0, 181);
randZhou = new Vector3(Random.Range(-1f,1f), Random.Range(-1f, 1f), Random.Range(-1f, 1f));
}
void Update()
{
//跟随center转圈圈
progress += Time.deltaTime * rotationSpeed;
if (progress >= 360)
{
progress -= 360;
}
float x1 = center.position.x + rotationRadius * Mathf.Cos(progress);
float y1 = center.position.y + rotationRadius * Mathf.Sin(progress);
Vector3 tmp = RotateRound(new Vector3 (x1,y1), center.position, randZhou, randAng);
this.transform.position = tmp;
}
/// <summary>
/// 围绕某点旋转指定角度
/// </summary>
/// <param name="position">自身坐标</param>
/// <param name="center">旋转中心</param>
/// <param name="axis">围绕旋转轴</param>
/// <param name="angle">旋转角度</param>
/// <returns></returns>
public Vector3 RotateRound(Vector3 position, Vector3 center, Vector3 axis, float angle)
{
return Quaternion.AngleAxis(angle, axis) * (position - center) + center;
}