【问题标题】:rigidbody.velocity is not working smoothly in unity刚体.速度在统一中工作不顺利
【发布时间】:2020-07-09 13:21:25
【问题描述】:

写了一个脚本来通过拖动来移动玩家,所以一开始,我用 transform.position 移动了玩家,它工作得很好,所以我说是时候用刚体移动它,让它与物体发生碰撞, 所以我尝试了rigidbody.velocity,但它移动不顺畅。那么如何使它像 transform.position 一样工作呢?

这是脚本:

void Update()
{
    if(Input.touchCount > 0)
    {
       Touch touch = Input.GetTouch(0);
     
        if (touch.phase == TouchPhase.Moved)
        {
            transform.position = new Vector3(
            transform.position.x + touch.deltaPosition.x * speedmodifier,
            transform.position.y,
            transform.position.z + touch.deltaPosition.y * speedmodifier);
             
        }
    }
}

【问题讨论】:

    标签: c# visual-studio unity3d 3d rigid-bodies


    【解决方案1】:

    当使用Rigidbody 时,您希望在FixedUpdate 中做所有与物理相关的事情。那么您可能不会使用velocity,而是使用Rigidbody.MovePosition 设置固定位置

    您仍然应该通过Update 获得用户输入。

    我会分开逻辑。可能是这样的

    [SerializeField] private Rigidbody _rigidbody;
    private Vector3 targetPosition;
    
    private void Start()
    {
        targetPosition = transform.position;
        if(!_rigidbody) _rigidbody = GetComponent<Rigidbody>();
        // since this rigibody is going to be moved via code not Physics it should be kinemtic
        _rigibody.isKinematic = true;
        // in order to smooth the movement
        _rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
    }
    
    void Update()
    {
        if(Input.touchCount > 0)
        {
           Touch touch = Input.GetTouch(0);
         
            if (touch.phase == TouchPhase.Moved)
            {
                targetPosition += Vector3.right * touch.deltaPosition.x * speedmodifier;
                targetPosition += Vector3.forward * touch.deltaPosition.y * speedmodifier;      
            }
        }
    }
    
    private void FixedUpdate()
    {
        _rigidbody.MovePosition(targetPosition);
    }
    

    【讨论】:

    • 它没有与物体发生碰撞。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多