SondreBBakken
SondreBBakken

Reputation: 173

Get new location from Quaternion and Vector3 in Unity

I have a Vector3 and a Quaternion, what is the best way to get the coordinates of a location a certain distance in front (or behind).

What I am trying to do is this:

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

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

Upvotes: 4

Views: 3454

Answers (3)

Programmer
Programmer

Reputation: 125375

The Ray struct and its GetPoint function is used to calculate an unknown distance by just providing the starting point, direction and the distance you want it to find.

Let's say this is the location and direction

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

Find distance in 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);

Upvotes: 1

Cenkisabi
Cenkisabi

Reputation: 1076

I didn't test but this should work

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

distance is unit length from gameObject here.

Edit:

So, there is no transform. And we should generate forward from quaternion. I looked how Unity3D calculate 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 a Quaternion rotation and you a Vec3 position as you said in question. So, you can convert this function like this:

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

Upvotes: 2

Riaan Walters
Riaan Walters

Reputation: 2676

If you multiply a world rotation with Vector3.forward you will get the same as using the respective transform.forward

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

You could use Ray but that would be overkill

Upvotes: 4

Related Questions