简体   繁体   中英

Is there a way to create a curve when launching a gameobject to the player?

This is what I have tried so far: I create a raycast and if it hits an object on layer 8 (the layer in which objects need to be launched to the player), I call the SlerpToHand() function.

    private void Update()
    {
        if(Physics.Raycast(transform.position, transform.forward * raycastLength, out hit))
        {
            if(hit.collider.gameObject.layer == 8)
            {
                // Launch object to player
                SlerpToHand(hit.collider.transform);
            }
        }
    }

Inside of SlerpToHand(), I set the object's position to Vector3.Slerp(), that vector being created from values in the hit object.

    private void SlerpToHand(Transform hitObj)
    {
        Vector3 hitObjVector = new Vector3(hitObj.transform.position.x, hitObj.transform.position.y, hitObj.transform.position.z);

        hitObj.position = Vector3.Slerp(hitObjVector, transform.position, speed);
    }

But the result of this is all wrong, the object just gets teleported to the player's hands. Is Vector3.Slerp() not a good way to curve an object to the player? For context I am trying to recreate Half-Life: Alyx's grabbity gloves. There is still some work to do with the hand gestures but I am just trying to get the object curve down. Help is much appreciated, let me know if more info is needed.

See unity docs :

public static Vector3 Slerp(Vector3 a, Vector3 b, float t);

Here, t is a normalized position between two input values. It means, if t = 0, result will be exactly first value. If t = 1, result will be exactly second value. If t = 0.5, result will be the middle between two values.

So, usually, you need to call Slerp every Update, step by step increasing t from 0 to 1. For this, usually Time.deltaTime used (which equals the time between updates). For speed control, multiply your speed by Time.deltaTime.

Update()
{
    if (t < 1)
    {
        t += Time.deltaTime * speed;
        hitObj.position = Vector3.Slerp(startPosition, endPosition, t);
    }
}

...and in this case, for start moving, you just need to set t = 0. Probably, you have to implement your own logic here, but this should show the idea.

In addition:

  • Slerp used to interpolate between vector directions, for positions use Lerp.
  • Consider use DOTween plugin - its free and powerful for such cases.

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