用鼠标拖动旋转和平衡HingeJoint2D

时间:2016-04-19 16:44:18

标签: unity3d unity3d-2dtools

我正在尝试实现物理,类似于这个游戏:

https://sites.google.com/site/newstudyhall/games/tilt-2

我有一个“手”精灵,它是Kinematic并且上面有一个HingeJoint2D。另一个不是运动学的精灵“棒”通过HingeJoint2D连接到手。我想通过移动手来平衡手上的棒。

我用手附上了以下脚本。我正在用鼠标拖动来移动手,并在鼠标移动的相反方向上施加力。但它不像上面提到的游戏那样工作。

Unity中是否有任何组件,我可以用它来产生这个结果,或者我该如何实现它?

private Vector3 screenPoint;
private Vector3 offset;


void FixedUpdate()
{
    //ON CLICK
    if (Input.GetButtonDown("Fire1"))
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));

    }

    //ON DRAG
    if (Input.GetButton("Fire1"))
    {
        Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);

        //HAND POSITION CHANGE WITH MOUSE DRAG
        Vector2 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
        transform.position = cursorPosition;

        //APPLY FORCE ON TRAY IN OPPOSITE DIRECTION OF MOUSE MOVEMENT
        GameObject.Find("Stick").GetComponent<Rigidbody2D>().AddForce(((cursorPosition.normalized * 5)) * -1, ForceMode2D.Impulse);

    }
}

1 个答案:

答案 0 :(得分:1)

我认为你可以使用rigidbody2d组件和gravity参数以非常简单的方式做这样的balacing。

Here is a link to a similar question with a very good answer that may help you