Unity c#将对象轻拂到方向,无论相机角度如何

时间:2018-12-08 13:56:27

标签: c# unity3d swipe

我有以下特定代码,可通过按所需方向滑动来向前滑动对象。问题是我的相机角度是旋转的,所以每当我将对象向中心或向左滑动时,滑动都不准确。当我在右侧的任意位置轻拂时,对象将被精确地抛出。我如何调整此代码,以便无论摄像机旋转如何,都可以将物体朝世界空间方向扔。谢谢。

代码:`公共类SwipeScript:MonoBehaviour {

public float force = 2f;
public bool isTarget = false;
public float zFactor = 2f;

public Vector3 startPosition;

private Vector2 startSwipe;
private Vector2 endSwipe;
private Rigidbody currentBoxRb;

void Start()
{
    currentBoxRb = StackerManager.currentBox.GetComponent<Rigidbody>();
    startPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
}
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        startSwipe = Camera.main.ScreenToViewportPoint(Input.mousePosition);
    }

    if (Input.GetMouseButtonUp(0))
    {

        endSwipe = Camera.main.ScreenToViewportPoint(Input.mousePosition);
        if (isTarget == true)
        {
            Swipe();
            isTarget = false;

        }


    }
}
void Swipe()
{
    Vector3 swipe = endSwipe - startSwipe;
    swipe.z = swipe.y / zFactor;
    swipe.y = -0.001f;
    currentBoxRb.isKinematic = false;
    currentBoxRb.AddForce(swipe * force, ForceMode.Impulse);

}

private void OnMouseDown()
{

    currentBoxRb.constraints = RigidbodyConstraints.None;
    isTarget = true;

}

}

0 个答案:

没有答案