简体   繁体   中英

rigidbody.velocity is not working smoothly in unity

wrote a script to move the player by dragging it, so at first, I moved the player with transform.position and it worked perfectly so I said its time to move it with rigidbody to make it collides with objects, so I tried rigidbody.velocity but it not moving smoothly. so how to make this works like transform.position?

this is the script:

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

When using Rigidbody you want to do all physics related stuff in FixedUpdate . then you probably would not use velocity but set fix positions using Rigidbody.MovePosition

You should still get the User input via Update though.

I would separate the logic. Something like maybe

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM