How to go about having two seperate Game Objects follow eachother?

So I have player Game Object, and a “beam” Game Object. The player is the white square in the bottom right, half covered by the “beam”. The "beam is the large blue rectangle.

Upon moving your mouse around the screen, the “beam” will spin around the player and point toward your mouse.

The player cannot move through those trees, but the beam can. Because I put them on separate layers, so the player and tree layer can collide, but the beam and tree layer cannot collide.

This beam will follow the player around with this code

this.GetComponent<Rigidbody2D>().velocity = owner.GetComponent<Rigidbody2D>().velocity;

“owner” is the player object.

Both player and beam have their own rigidbodies and colliders. They are not a parent or child of eachother.

So the problem is. If our player here holds “w”(up) and runs into the trees, and can no longer move. The beam will keep going up. Or two players both have beams extending from them and walk toward each other. The beams will stop and collide(as they should), but the players will keep moving toward each other, passing through the beams( I do not want this to happen).

I cannot find a solution that lets the beam follow the player while abiding by the players movement, and opposite, the player abides by the beams movement. Basically, if the beam cant move, nor should the player, if the player cant move, nor should the beam.

Any ideas on how I go about coding/making this interaction would be very helpful. Thanks

Hey there @safetyfirststudios,

There is multiple solution for your issue, I’ll suggest one of them:

Add the beam as a child for the player then replace your code

 this.GetComponent<Rigidbody2D>().velocity = owner.GetComponent<Rigidbody2D>().velocity;


Vector3 mousePos = Input.mousePosition;
Vector3 mousePosWorld = Camera.main.ScreenToWorldPoint(mousePos);

//beam transform
//Vector3.left or Vector3.up depends on ur local transform beam direction
transform.LookAt(mousePosWorld, Vector3.left);

Now the beam will always rotate towards the mouse without moving when the player collide.