- Home /
Question by
GlordFingle · Jun 26, 2020 at 10:57 PM ·
c#physicsrigidbody
How do I add a pulling force?
So, my character is a ball, and you solve puzzles by pushing cubes, (and more) but if you push a cube or ball into a wall, you can't move it. So I thought of adding a pulling thing, where is I press a button, it pulls objects to me, my problem, is that I can't/don't know how to do this. So could anyone help me with this?
Comment
Answer by markythemurloc · Jun 26, 2020 at 11:28 PM
Hey! Not sure how your code looks like, but off the top of my head I have 3 possible solutions that may work.
1. Make the object you want you 'pull' a child of the pulling object. A child will move as one with its parent.
2. Use Vector2.MoveTowards.
3. Add force in the desired direction.
//Set parent.
if (Input.GetKeyDown(KeyCode.X))
{
transform.SetParent(pullingObject.transform);
}
//In order to detach a child from a parent
if (Input.GetKeyUp(KeyCode.X))
{
transform.SetParent(null);
}
//Vector2.MoveTowards. Should be place in a FixedUpdate/Update.
if (Input.GetKeyDown(KeyCode.X))
{
transform.position = new Vector2.MoveTowards(transform.position, pullingObject.transform.position, speed)
}
//Add force in desired direction.
//Negative X to move left, negative Y to move down.
//Move left for example:
transform.GetComponent< Rigidbody2D>().AddForce(new Vector2(-5f, 2f));
Hopefully this helps, good luck.
Your answer
![](https://koobas.hobune.stream/wayback/20220613001902im_/https://answers.unity.com/themes/thub/images/avi.jpg)