[英]Unity2D - How to move AND rotate a gameobject around a circle in a 2D game?
我正在嘗試圍繞目標行星(目前只是一個圓圈)移動和旋轉一些雲。 我把運動放下了,但我真的在旋轉部分掙扎。 我希望它根據它在圓圈上的位置按比例旋轉,但我一直在試圖猜測正確的數字。 這是代碼:
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);
}
}
你可以! 通過不斷改變 x 比例! 在更新無效時調用此函數
public void Rotate()
{
if (transform.localScale.x <= -1)
{
rotationBool = true;
}
if (transform.localScale.x >= 1)
{
rotationBool = false;
}
if (rotationBool == false)
{
Vector3 scaleChange = new Vector3(0.01f, 0f, 0f);
transform.localScale -= scaleChange;
}
if (rotationBool == true)
{
Vector3 scaleChange = new Vector3(0.01f, 0f, 0f);
transform.localScale += scaleChange;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.