Unity2D-如何在2D游戏中围绕圆形移动和旋转游戏对象? [英] Unity2D - How to move AND rotate a gameobject around a circle in a 2D game?
问题描述
我正在尝试围绕目标行星(目前只是一个圆圈)移动和旋转一些云.我的机芯下降了,但是我真的在旋转部分上挣扎.我希望它与圆上的位置成比例旋转,但是我一直试图猜测正确的数字.这是代码:
I'm trying to move and rotate some clouds around a target planet (which is just a circle at the moment). I got the movement down, but I am really struggling with the rotation part. I want it to rotate in proportion to where it is on the circle but I'm stuck trying to guesstimate the right numbers. Here is the code:
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
函数
A more recent option, baked into Unity -- you can also try RotateAround
function
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 &
浮点角(以度为单位).
transform.RotateAround()
takes a Vector3
Point
Axis&
float Angle` in degrees.
轴为旋转方向.
同一件事,带有一个工作示例,从这里开始
Same thing, with a working sample from here
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);
}
}
这篇关于Unity2D-如何在2D游戏中围绕圆形移动和旋转游戏对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!