- Home /
how to move a gameobject's x position when another gameobject's x position is being moved?
My problem is I have a circle that is not moving along with a box x position(haven't worked on any artwork yet trying to get the gameplay working first) when the circle lands on the box & I move the box x position the circle stays where it is & falls when it isn't touching the box anymore. I want to move it along with the box from where it landed with out it having to be a child if possible.
public bool touching;
public GameObject box;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Box")
{
touching = true;
rb.constraits = RigidbodyConstraits2D.FreezeRotation;
}
}
void Update()
{
if (touching)
{
Vector2 pos = transform.position;
pos.x = box.transform.position.x - pos.x;
}
}
I dont get exactly what are you asking (confused with you explanation... :D)
Why not just call a function (that moves the circle) when move the box?
Answer by highpockets · Sep 30, 2019 at 07:58 AM
Like @tormentoarmagedoom , I am also confused with your explanation, but looking at the last line of your code where you apply box.transform.position.x - pos.x to pos.x is really just applying the length between the 2 objects on the x axis and not giving you the correct x value in world space.
You want to get the circle’s x position relative to the box’s x position when the circle lands on the box and to do that without being a child you just save it when the collision happens:
float relativeXPos;
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == “Box”)
{
relativeXPos = box.transform.position.x + (box.transform.position.x - transform.position.x) ;
}
}
Thereafter, to update the circle x position relative to the box x position, all you need to do is apply what you saved in the collision to the current position:
transform.position = box.transform.position + relativeXPos;
Hope that helps