calculating my position from another object

I want to use another object and be an exact distance away from it.

What I want basically is my position to be +2 on the y axis alongside the other object

I raycast down, to see where the object is (in this time the object itself is falling) when it reaches it I want it to take it’s place +2 on the y axis from the object it’s raycasting on

Here is what I have so far

void FixedUpdate(){

RaycastHit hit;
		Vector3 otherObjectPosition;

		//Vector3 direction = transform.TransformDirection(-Vector3.up);
		if (Physics.Raycast(transform.position, -Vector3.up, out hit, 2, ~layerToIgnore)){
			otherObjectPosition = hit.collider.gameObject.transform.position;
			Vector3 temp = transform.position;
//			transform.position.y = otherObjectPosition.y -= -2;

			temp.y = otherObjectPosition.y -= 2;
		} else {
	public void MoveDown(){

			transform.Translate(Vector3.down * Time.deltaTime, Space.World);


Can someone help me with this because it isn’t doing what I’m expecting to do and I can’t seem to get it to work.


Jan Julius.

I’m assuming the raycasting itself works correctly.

There are 2 problems here:

//          transform.position.y = otherObjectPosition.y -= -2;

You can’t change just one part of a transform.position like that, you can only get its value; and second, I don’t know why you’re trying to update otherObjectPosition.y by subtracting -2 from it and only then passing this to your transform position, when you just want to change your transform.position.

this should work:

Vector3 temp;
temp = new Vector3(otherObjectPosition.x, otherObjectPosition.y+2, otherObjectPosition.z);
this.transform.position = temp;

What it does it creates a new Vector3 with all 3 coordinates set to the other object’s position in X and Z axes, and +2 its Y axis position.

Alternatively you could just take the other object’s position and add a vector to it, like:

this.transform.position = otherObjectPosition + new Vector3(0.0f, 2.0f, 0.0f);

That is if I understood correctly what it is you’re trying to achieve.

Hope it helps