c# - Unity2D - 如何在 2D 游戏中围绕圆圈移动和旋转游戏对象?
问题描述
我正在尝试围绕目标行星(目前只是一个圆圈)移动和旋转一些云。我降低了动作,但我真的在旋转部分苦苦挣扎。我希望它与圆上的位置成比例旋转,但我一直试图猜测正确的数字。这是代码:
public class CloudMovement : MonoBehaviour
{
public GameObject target;
private float RotateSpeed = .05f;
private float Radius = 1.0f;
private Vector2 center;
private float angle;
private void Start()
{
center = target.transform.localPosition;
Radius = target.transform.localScale.x / 1.5f;
}
private void Update()
{
angle = angle + RotateSpeed * Time.deltaTime;
this.transform.Rotate (Vector3.forward * -angle * Time.deltaTime);
Vector2 offset = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle)) * Radius;
this.transform.position = center + offset;
}
}
解决方案
using UnityEngine;
public class CloudMovement : MonoBehaviour
{
// X Y radius
public Vector2 Velocity = new Vector2(1, 0);
// rotational direction
public bool Clockwise = true;
[Range(0, 5)]
public float RotateSpeed = 1f;
[Range(0, 5)]
public float RotateRadiusX = 1f;
[Range(0, 5)]
public float RotateRadiusY = 1f;
private Vector2 _centre;
private float _angle;
private void Start()
{
_centre = transform.position;
}
private void Update()
{
_centre += Velocity * Time.deltaTime;
_angle += (Clockwise ? RotateSpeed : -RotateSpeed) * Time.deltaTime;
var x = Mathf.Sin(_angle) * RotateRadiusX;
var y = Mathf.Cos(_angle) * RotateRadiusY;
transform.position = _centre + new Vector2(x, y);
}
void OnDrawGizmos()
{
Gizmos.DrawSphere(_centre, 0.1f);
Gizmos.DrawLine(_centre, transform.position);
}
}
编辑选项 2:RotateAround
一个更新的选项,融入 Unity - 你也可以尝试 RotateAround
函数
Vector3 point = new Vector3(10,0,0);
Vector3 axis = new Vector3(0,0,1);
transform.RotateAround(point, axis, Time.deltaTime * 10);
transform.RotateAround()
以度为单位采用Vector3
Point
Axis &
float Angle`。
轴是旋转方向。
同样的事情,这里有一个工作样本
public class CloudMovement : MonoBehaviour {
public float speed;
public Transform target;
private Vector3 zAxis = new Vector3(0, 0, 1);
void FixedUpdate () {
transform.RotateAround(target.position, zAxis, speed);
}
}
推荐阅读
- php - 带有 API 平台的 Doctrine 查询结果缓存
- python - 在 NLTK 中进行标记时如何忽略特殊字符?
- html - 如何将 404 重定向到主页
- amazon-web-services - AWS Athena \ Glue 上的希伯来语编码
- c++ - 我不知道我在 FindLargest 函数中做错了什么
- ruby-on-rails - Authlogic gem:在会话级别而不是在用户级别使用 last_request_at 列
- sql-server - 使用 mod_proxy 通过反向代理连接到 SQL Server 的正确连接字符串是什么(
)]? - splunk - 如何在 splunk 中获取一个字段值的每小时总和
- typo3 - TYPO3 流体:从页面获取所有内容 ID
- multithreading - 为什么多线程时间不等于 gunicorn 的单个处理时间?