One challenge we had was getting the player to jump appropriately. As a placeholder, in our player movement script we started with this code for jumping:
public class moveExample : MonoBehavior {
...
public float moveJump = 0.5f;
...
void Update()
{
...
if(Input.GetKeyDown (KeyCode.W)){
transform.Translate (0,moveJump,0);
}
}
}
This kind of worked, but there are several problems with it.
- You can keep pressing the jump key, and do some weird looking midair jumps.
- When jumping, the player would actually disappear from the ground, and reappear in a new location higher up.
So for the first issue, I added the following code to make it so the player could only jump while on contact with the ground:
public class moveExample : MonoBehavior {
...
public float isGrounded = false;
...
void Update()
{
...
if(Input.GetKeyDown (KeyCode.W) && isGrounded == true){
transform.Translate (0,moveJump,0);
}
}
void OnCollisionStay2D(Collision2D collision)
{
if(collision.gameObject.tag == "Ground"){
isGrounded = true;
}
}
void OnCollisionExit2D(Collision2D collision)
{
if(collision.gameObject.tag == "Ground"){
isGrounded = false;
}
}
}
I also added a "Ground" tag in Unity and added that tag to the different objects that the player could land on.
For the second issue, what I really needed to do was add a force to the player instead of changing its physical location, which looked something like this:
public class moveExample : MonoBehavior {
...
public float moveJump = 200f;
...
void Update()
{
...
if(Input.GetKeyDown (KeyCode.W) && isGrounded == true){
rigidbody2D.AddForce (transform.up * moveJump);
}
}
}
Just like that, our player now jumps, and can easily be adjusted as desired with some physics tweaks.
No comments:
Post a Comment