Reputation: 5246
Update I've discovered that rigidbody doesn't cast to rigidbody2d. I've tried manually casting, but get errors saying that it can't be done... So my new question is, how can I get joints to work with rigidbody2D?
OP
Learning Unity and am now playing with physics. I've got a small game running and it's all working lovely, but what I'm having issues wrapping my head around is the 2D physics.
I've got various "crates" and each have their own physics values (gravity etc).I've also got a "crate mover" which will (in theory) move crates from one place to another.
However, due to my movers having defined positions they can move to in game space, I'm having terrible trouble getting the crates to "stick" to the movers when they're moved.
So, I did some digging around and found Joints
- Specifically FixedJoint
- I figured that would solve it, if I attached a joint to the mover and set it's body to the crate? Right? No.
I get this error:
NullReferenceException: Object reference not set to an instance of an object
RobertMover.OnCollisionEnter2D (UnityEngine.Collision2D coll) (at Assets/Scripts/RobertMover.cs:29)
Which relates to the following code:
void OnCollisionEnter2D(Collision2D coll)
{
Debug.Log (coll.gameObject);
FixedJoint j = (FixedJoint)this.gameObject.AddComponent ("FixedJoint");
j.connectedBody = coll.gameObject.rigidbody; // problem line
}
Seeing as I'm still learning Unity, I'm a little unsure as to what is null. My crate has a rigidbody. As does my mover, as I read that joints require them. The object isn't null (checked with the Debug.Log...). The only thing I can think is that the Joint itself is null, which is very odd!
Can anyone explain what I'm doing wrong?
Upvotes: 0
Views: 223
Reputation: 64477
2d physics only works with "2d" classes and methods, you should be using FixedJoint2D or a comparable "2D" joint class if that particular one doesn't exist
Upvotes: 1