使用鼠标拖动旋转和平衡HingeJoint2D



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

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

我有一个"手"精灵,它是运动学的,上面有一个铰链关节2D。另一个精灵"棒",它不是运动学的,通过铰链关节2D连接到手。我想通过移动手来平衡手头的棍子。

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

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);
    }
}

我认为可以使用rigidbody2d组件和重力参数以非常简单的方式进行平衡。

这里有一个链接到一个类似的问题,有一个很好的答案,可以帮助您

最新更新