Struggling to control rigidbody2d constraints from script

Hi,

Forgive the my first post inevitably being being a stupid question, … but, why can’t I change the RigidbodyConstraints2D from inside this script.

It seems simple enough, a ball moves back and forth at the top of the screen, controlled by the left and right arrows, then drops when the space barf is pressed. I’m just struggling with the RigidbodyConstraints2D function.

The rigid body is linked to the script.

Thankyou in advance for any help

public class Ballmove : MonoBehaviour
{

public Rigidbody2D myrigid;
public bool held;
public bool left;
public int speed;// Start is called before the first frame update
void Start()
{
myrigid = new Rigidbody2D();
held = true;
left = true;
speed = 3;

}
// Update is called once per frame
void Update()
{
if (held == true)
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
left = false;
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
left = true;
}
if (Input.GetKeyDown(KeyCode.Space))
{
held = false;
myrigid.constraints = RigidbodyConstraints2D.None;
}

if (left == true)
{

this.gameObject.transform.Translate(new Vector3(-1,0) * speed * Time.deltaTime);

}
else
{
this.gameObject.transform.Translate(new Vector3(1, 0) * speed * Time.deltaTime);
}

}

}
}

The Rigidbody2D constraints can do nothing if you bypass physics and the Rigidbody2D and directly write to the Transform; that’s the role of the Rigidbody2D and is explained in nearly all beginner 2D physics tutorials i.e. use the Rigidbody2D to cause movement.

Do not modify the Transform.

FYI: Here’s how to post code on the forums: Using code tags properly

Thanks for the help.
I was trying to take shortcuts and shot myself in the foot.
I’ve got it working and the link is appreciated.

1 Like