Get a new location from Quaternion and Vector3 in Unity

I have Vector3 and Quaternion, which is the best way to get the coordinates of a location some distance ahead (or behind).

I am trying to do the following:

Gizmos.color = Color.red;
var direction = transform.TransformDirection(Vector3.forward) * 1000;
Gizmos.DrawRay(transform.position, direction);

      

Just no access to transform, but with rotation (Quaternion) and coordinates (Vector3)

+3


source to share


3 answers


If you multiply the turnover of the world with Vector3.forward

, you get the same as with the corresponding transform.forward

public Vector3 GetPosition(Quaternion rotation, Vector3 position, float distance)
{
    Vector3 direction = rotation * Vector3.forward;
    return position + (direction  * distance);
}

      



You can use Ray

but that would be overkill

+2


source


I haven't tested but this should work

Vec3 location = transform.forward*distance + transform.position;

      

distance is the block length from the gameObject.

Edit:



So there is no transformation. And we have to generate forward from the quaternion. I looked at how Unity3D calculates transform.forward and found it here: Unity3D Transform

public Vector3 forward
{
    get
    {
        return this.rotation * Vector3.forward;
    }
    set
    {
        this.rotation = Quaternion.LookRotation(value);
    }
}

      

You have the quaternion rotation and you have the Vec3 position you were talking about. So you can transform this function like this:

Vec3 location = rotation*Vector3.forward*distance + position;

      

+2


source


Ray

struct and is GetPoint

used to calculate the unknown distance by simply specifying the starting point, direction and distance you want to find.

Let's say this is location and direction

Vector3 startingPostion = new Vector3(4, 6, 2);
Quaternion theDirection = Quaternion.identity;

      

Find the distance 100 meters.

Ray ray = new Ray();
//Set the starting point
ray.origin = startingPostion;
//Set the direction
ray.direction = Vector3.forward + theDirection.eulerAngles;

//Get the distance 
ray.GetPoint(100);

      

or

Ray ray = new Ray(startingPostion, worldRotation * Vector3.forward);
//Get the distance 
ray.GetPoint(100);

      

+1


source







All Articles