Collider2D and Rigidbody2D, how do they work?
Posted
by
user42646
on Game Development
See other posts from Game Development
or by user42646
Published on 2014-02-24T22:02:34Z
Indexed on
2014/06/11
21:43 UTC
Read the original article
Hit count: 150
I have been learning JavaScript and Unity for a week now. I learned how to make Cube as a Ground and another Cube as a player and I used this code to make the Player Cube move forward and backward and jumping
var walkspeed: float = 5.0;
var jumpheight: float = 250.0;
var grounded = false;
function Update() {
rigidbody.freezeRotation = true;
if (Input.GetKey("a"))
transform.Translate(Vector3(-1, 0, 0) * Time.deltaTime * walkspeed);
if (Input.GetKey("d"))
transform.Translate(Vector3(1, 0, 0) * Time.deltaTime * walkspeed);
if (Input.GetButton("Jump")) {
Jump();
}
}
function OnCollisionEnter(hit: Collision) {
grounded = true;
}
function Jump() {
if (grounded == true) {
rigidbody.AddForce(Vector3.up * jumpheight);
grounded = false;
}
}
I also learned how to make a character hit box. how to make a sprite and animation. pretty much the basic stuff.
Couple of days ago I created simple ground in Photoshop and a simple character and imported them to Unity3D. Whenever I use my code above the character keeps falling from the scene. Like the character has nothing to stand on. After thinking about it it make sense because I really didn't make anything to make the player character understand that he should stand on something so I started reading about this issue and I realized that there is something called Collider2D
and Rigidbody2D
.
Now I'm really stuck here I just don't know what to do. I applied the rigibody2d
to my character picture and the Collider2D
to the ground picture but whenever I play the project the gravity makes my character falls down.
This is my question:
How can I make the rigibody2d
object realize that it shouldn't fall if there is a Collider2D
object under it? So when I jump it's going to jump and the gravity going to bring it back to the ground.
© Game Development or respective owner