将对象拍摄到鼠标位置方向

时间:2017-11-13 12:39:20

标签: unity3d

我想强制我的对象到我的鼠标位置,我的意思是强迫它在我的对象和鼠标位置之间的方向,我使用这个代码:

if(Input.GetKeyDown(KeyCode.Space))
{
    GetComponent<Rigidbody2D>().velocity = Vector2.zero;
    Vector2 direction = (Vector2)(transform.position - Input.mousePosition);
    direction.Normalize();

    this.GetComponent<Rigidbody2D>().AddForce(-direction, ForceMode2D.Impulse);
}

但似乎它无法正常运作......

2 个答案:

答案 0 :(得分:1)

这应该有效:

    if(Input.GetKeyDown(KeyCode.Space))
    {
        this.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
        Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);
        Vector2 direction = (Vector2)(Input.mousePosition-screenPoint);
        direction.Normalize();

        this.GetComponent<Rigidbody2D>().AddForce(direction, ForceMode2D.Impulse);
    }

答案 1 :(得分:-2)

如果你想要一个更好的控制运动,你也可以使用iTween:

http://www.pixelplacement.com/itween/index.php