【问题标题】:Moving ball from ball own position Unity3D从球自己的位置移动球Unity3D
【发布时间】:2019-06-28 20:36:01
【问题描述】:

我想用鼠标移动我的球,目前球跟随鼠标位置,我想跟随鼠标的行为而不是位置。

我试图以速度移动,但我正在使用速度移动我的球前言,所以它的行为出乎意料。

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

此代码用于根据鼠标移动球,但我不想跟随鼠标的位置。我只需要像左右上下一样跟随。

【问题讨论】:

  • 我可能会使用 AddForce 方法来解决这个问题。向鼠标从前一帧移动到本帧的向量中的球添加力。

标签: unity3d


【解决方案1】:

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

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

【讨论】:

  • 那么你必须做类似的事情,但是改变速度。从概念上讲,应该是同一件事;检查上一帧和这一帧之间的鼠标位置差异,并将其添加到当前速度向量。
猜你喜欢
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多