从球自己的位置移动球Unity3D

时间:2019-06-28 12:11:29

标签: unity3d

我想使用鼠标来移动我的球,当前球跟随鼠标的位置,我想跟随鼠标的行为,但不跟随位置。

我试图通过速度来移动,但是我正在使用速度来移动我的球序,因此它的表现出乎意料。

 private void Update()
  {
    rigid.velocity = new Vector3(0f, -2f, Time.deltaTime * speed);
      if (Input.GetMouseButton(0))
     {
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit;
         if (Physics.Raycast(ray, out hit))
          {
            Vector3 point = hit.point;

            rigid.MovePosition(new Vector3(Mathf.Lerp(transform.position.x,Mathf.Clamp(point.x, -3, 3),5 * Time.deltaTime), transform.position.y, transform.position.z));

        }
    }

    if (Input.touchCount > 1)
    {
        Touch touch = Input.GetTouch(0);
        switch (touch.phase)
        {
            case TouchPhase.Moved:
                rigid.MovePosition(new Vector3(Mathf.Lerp(transform.position.x, Mathf.Clamp(touch.position.x, -3, 3), 5 * Time.deltaTime), transform.position.y, Mathf.Lerp(transform.position.z, touch.position.y, 5 * Time.deltaTime)));
                break;
        }
    }
}

此代码用于根据鼠标移动球,但是我不想跟随鼠标的位置。我只需要遵循左右左右的行为即可。

1 个答案:

答案 0 :(得分:0)

我还没有尝试过,但是从概念上说是这样的:

Vector2 prevMousePos = Vector2.zero;
private float power = 10; // Change this to edit power

private void Update()
{
    if (Input.GetMouseButton(0))
    {
        Vector2 mousePos = Input.mousePosition;
        Vector2 direction = (mousePos - prevMousePos).normalized;
        rigid.AddForce(direction * power);
        prevMousePos = mousePos;
    }
}

请注意,如果像代码当前所做的那样,每Update()设置“速度”,它将覆盖所有其他物理运动。您也可以通过以恒定的运动方式执行AddForce来解决此问题,然后确保对象不会无限快地移动,添加速度检查并限制速度:

const float MAX_VELOCITY = 10;

void Update() 
{
    /* 
     * ... Input.GetMouseButton(0) ...
     */

    // Add force in the direction you today have set for rigid.velocity
    rigid.AddForce(new Vector3(0f, -2f, Time.deltaTime * speed));

    // Make sure the AddForce doesn't goes faster than MAX_VELOCITY
    if (rigid.velocity.magnitude > MAX_VELOCITY) 
    {
        rigid.velocity = rigid.velocity.normalized * MAX_VELOCITY;
    }
}