刚体圆周运动

时间:2019-09-04 15:20:44

标签: c# unity3d

我有一个2D球,该球具有一定的力并且可以沿不确定的方向移动,我需要使用户在触摸屏幕时,球相对于当前方向相对于当前方向向右或向左或向右圆形移动。我该怎么办?

我尝试了这段代码,但是其他物理学无法影响球,因为我们直接更改了转换:

float angle = 0;
float radius = 1;

void FixedUpdate()
{
    angle += speed * Time.deltaTime;
    float x = center.x + Mathf.Cos(angle) * radius;
    float y = center.y + Mathf.Sin(angle) * radius;

    rigidbody.transform.position = new Vector3(x, y, 3);
}

2 个答案:

答案 0 :(得分:4)

就像物理学一样:

您的触摸位置就是一个重力中心→以相同的幅度连续分配一个新方向,但该新方向应与从中心到运动物体和旋转轴的矢量成90°角。

在代码中看起来像

public class Example : MonoBehaviour
{
    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Camera _camera;

    [SerializeField] private Vector2 initialVelocity;    

    private bool doGravitation;
    private Vector2 centerPos;

    private void Awake()
    {
        if(!rb) rb = GetComponent<Rigidbody2D>();
        if(!_camera) _camera = Camera.main;

        rb.velocity = initialVelocity;
    }

    private void Update()
    {
        // check for touch support otherwise use mouse as fallback
        // (for debugging on PC)
        if (Input.touchSupported)
        {
            // not touching or too many -> do nothing
            if (Input.touchCount != 1)
            {
                doGravitation = false;
                return;
            }

            var touchPosition = Input.GetTouch(0).position;
            centerPos = _camera.ScreenToWorldPoint(touchPosition);
            doGravitation = true;
        }
        else
        {
            // mouse not pressed -> do nothing
            if (!Input.GetMouseButton(0))
            {
                doGravitation = false;
                return;
            }

            centerPos = _camera.ScreenToWorldPoint(Input.mousePosition);
            doGravitation = true;
        }
    }

    private void FixedUpdate()
    {
        if(!doGravitation) return;

        // get current magnitude
        var magnitude = rb.velocity.magnitude;

        // get vector center <- obj
        var gravityVector = centerPos - rb.position;

        // check whether left or right of target
        var left = Vector2.SignedAngle(rb.velocity, gravityVector) > 0;

        // get new vector which is 90° on gravityDirection 
        // and world Z (since 2D game)
        // normalize so it has magnitude = 1
        var newDirection = Vector3.Cross(gravityVector, Vector3.forward).normalized;

        // invert the newDirection in case user is touching right of movement direction
        if (!left) newDirection *= -1;

        // set new direction but keep speed(previously stored magnitude)
        rb.velocity = newDirection * magnitude;
    }
}

另请参阅:

enter image description here


请注意,这有时看起来很奇怪,尤其是在碰到球的前面时,因为我们将其逼到可能与当前运动成奇怪角度的圆曲线上。您可以解决这个问题,但这取决于您;)

答案 1 :(得分:0)

如果您不让它沿自己的轴线移动,则必须将其连接到另一个物体上,但是要将球放置在与球相同的位置。您可以隐藏皮革,然后在自动旋转时,它会移动隐藏身体的轴。这是无需额外编码或不面临四元数问题的最佳方法。