rigidbody rotatetowards

hey, how do you get maxDegreesDelta?
im trying to make a rigidbody rotateTowards a click but havent had much luck aside from using Quaternion.LookRotation(which is great but too snappy). help pls

    private void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            bool hitSomething = Physics.Raycast(ray, out RaycastHit hitInfo);

            if (hitSomething)
            {
                Vector3 clickedWorldPoint = hitInfo.point;
                _rigidbody.AddForce((clickedWorldPoint - transform.position).normalized * moveSpeed);

                float singleStep = rotationSpeed * Time.deltaTime;
                //Vector3 targetDirection = _rigidbody.position - clickedWorldPoint;
                //Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 1.0f);
                //transform.rotation = Quaternion.LookRotation(newDirection);

                _rigidbody.transform.rotation = (Quaternion.RotateTowards(transform.position, clickedWorldPoint, ??));


                //_rigidbody.transform.rotation = (Quaternion.LookRotation(clickedWorldPoint - transform.position));

            }
        }
    }

With your code, if your raycast was successful then the code to rotate the object is only executed for that frame.

As you don’t want it to just snap to a rotation, calc a target rotation if your raycast is successful, store it in a variable and then lerp or rotate towards that each frame.

1 Like

wow, yea youre right. thx for pointing that out. how do you store a variable? (sry for such a noob question… using ‘clickedWorldPoint’ outside of this if statement has been giving me errors lol)

In the same way you store a reference to the rigid body component.

public float RotationSpeed = 2f;

private Camera _mainCam;
private Vector3 _hitPoint;
private Quaternion _targetRot;

private void Start()
{
    _mainCam = Camera.main;
    _targetRot = transform.rotation;
}

private void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        var ray = _mainCam.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out RaycastHit hitInfo))
        {
            _hitPoint = hitInfo.point;

            _targetRot = Quaternion.LookRotation(_hitPoint - transform.position, Vector3.up);
        }
    }

    transform.rotation = Quaternion.Lerp(transform.rotation, _targetRot, RotationSpeed * Time.deltaTime);
}
1 Like

duude. it makes so much sense now. you put the information you want at the beginning so even if it goes through the IFs and what else you can still pull it out and slap it onto a different function. aaaha, its so obvious! you da bes.
with this new info i was able to move things around so the input is taken in by Update and the physics magic is school bussed through FixedUpdate :smile: YES. also the rotation is smooth as butta, tysm.