How to make an object position copy another object position?

It looks simple,i know,but i just can’t do it.
Im making a telekinesis game,where the player can push and pull objects from afar.

I need to make a script that,once the player aim and pull an object,it copies the position (of a game object i have in the middle of the screen) on TWO axis (X,Y),so it will float around but will not come to the direction of the player.

I have a pretty big script here,i don’t think i need to post it.

All you need to know is; the object i will drag around is a simple gameObject ,and the object in the middle of the screen (for reference the object position and etc) is a Transform. I simply want to make the object i pull to copy the object in the middle of the screen.

i thought i could just make something like:

ObjectToPull.transform.position.x = ObjectToCopyPosition.transform.position.x;

but it does not work,i get an error saying i can’t modify the transform.position because it is not a variable or something like that…
Any ideas are appreciated.
Thanks.

You need to rewrite the whole position vector at once:

float x = ObjectToCopyPosition.transform.position.x;
float y = ObjectToPull.transform.position.y;
float z = ObjectToPull.transform.position.z;

ObjectToPull.transform.position = new Vector3(x, y, z);
2 Likes

Hey friend thanks for the answer,it helped me a lot!!!

It’s actually working much better now.
I would like to know if there is any way i can make the transform smoother? using something like lerp?

Yep! I would suggest a coroutine and Vector3.MoveTowards:

public float MovementSpeed = 5f;
boolean isMoving = false;

IEnumerator MoveObjectOverTime(Transform moveMe, Vector3 target, float speed) {
  if (isMoving) yield break;
  isMoving = true;
  Debug.Log($"Starting to move {moveMe.name} from {moveMe.transform.position} to {target}.");
  while (moveMe.transform.position != target) {
    Vector3 currentPosition = moveMe.transform.position;
    Vector3 newPosition = Vector3.MoveTowards(currentPosition, target, speed * Time.deltaTime);
    moveMe.transform.position = newPosition;
    yield return null;
  }

  Debug.Log($"Done moving {moveMe.name}!");
  isMoving = false;
}

Then where your other code was:

float x = ObjectToCopyPosition.transform.position.x;
float y = ObjectToPull.transform.position.y;
float z = ObjectToPull.transform.position.z;
Vector3 target = new Vector3(x, y, z);
StartCoroutine(MoveObjectOverTime(ObjectToPull.transform, target, MovementSpeed);