Get position relative to transform.forward

Not sure if this is the right spot.

Moving an object to a random spot and in a random direction.
Have a second object that starts in a relative position to the first.
It cant be parented etc so this has to be done in code.
I have reference to the position of the second object.
I need to get have the second object maintain its relative position to the first, relative to the first objects forward vector.
eg Second object is up and to the left at the start, whenever object one changes position, object two needs to always be up and to the left of object one.

I know how to get direction and magnitude of the second object at the start, but just cant figure out how to apply it to the first objects new transform.forward.

Any ideas would be appreciated.

I presume you’re not talking about any Physics components here (2D or 3D) but just Transforms? If so then no, it’s not a Physics thing and should be posted on the Scripting forum.

I can move your post for you if you wish.

Yes please and thanks

I’m not sure about precisely what you want, but let me drop some tidbits on you to perhaps guide you to success.

Every Transform has some shortcuts as you note, such as transform.forward and transform.right

If I am sitting in your scene and I want to spawn something ahead of me 5 meters and to my right 2 meters, here would be how I would do that:

// Drag the Kurt object in here
public Transform Kurt;

// set these up with values you want, using the inspector
public float ahead = 5.0f;
public float right = 2.0f;

Now we place something 5 meters ahead of Kurt and 2 meters to his right.

Vector3 KurtPosition = Kurt.position;

Vector3 spawnPosition = KurtPosition +
    Kurt.forward * ahead +
    Kurt.right * right;

// TODO: use spawnPosition to make your thing
GameObject thing = Instantiate<GameObject>( ThingPrefab, spawnPosition, Kurt.rotation);

That third term will also rotate the object to match Kurt’s rotation.

1 Like

Thanks Kurt, that was the missing piece. I had figured I had to break down the vector, and that the forward direction was one component. I didn’t think of using transform.right (and in this instance transform.up for 3d Vector). The rest was easy then:

7945294--1016731--upload_2022-3-7_6-1-19.png