2D Game update
- Keshav Batra
- Mar 17, 2022
- 2 min read
I've finally finished all the 2D platformer lessons. My game is also bug free and so now all the animations work properly. The last thing I've added was a coyote jumping feature where I can jump 3 times more than I usually could. It's helped me avoid enemies attacks. I've also edited the camera to move only when I enter another room so that it's the style of enemies being fought and then moving on to the next room. Below is some of the code and footage that I have done.
private void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
//Flips the player when moving right and left
if (horizontalInput > 0.01f)
transform.localScale = Vector3.one;
else if (horizontalInput < -0.01f)
transform.localScale = new Vector3(-1,1,1);
//Set animator parameters
anim.SetBool("Run", horizontalInput != 0);
anim.SetBool("Grounded", isGrounded());
//Jump
if (Input.GetKeyDown(KeyCode.Space))
Jump();
//Adjustable jump height
if (Input.GetKeyUp(KeyCode.Space) && body.velocity.y > 0)
body.velocity = new Vector2(body.velocity.x, body.velocity.y / 2);
if (OnWall())
{
body.gravityScale = 0;
body.velocity = Vector2.zero;
}
else
{
body.gravityScale = 5;
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
if (isGrounded())
{
coyoteCounter = coyoteTime; //Reset the coyote counter when on the ground
jumpCounter = extraJumps; //Reset jump counter to extra jump value
}
else
coyoteCounter -= Time.deltaTime; //Start decreasing coyote counter when not on the ground
}
}
private void Jump()
{
if (coyoteCounter < 0 && !OnWall() && jumpCounter <=0) return; //If coyote counter is 0 or less and not on the wall dont do anything
SoundManager.instance.PlaySound(jumpSound);
if (OnWall())
WallJump();
else
{
if (isGrounded())
body.velocity = new Vector2(body.velocity.x, jumpPower);
else
{
//If not on the ground and coyote counter bigger than 0 do a normal jump
if (coyoteCounter > 0)
body.velocity = new Vector2(body.velocity.x, jumpPower);
else
{
if(jumpCounter > 0) //If there are extra jumps then jump and decrease the jump counter
{
body.velocity = new Vector2(body.velocity.x, jumpPower);
jumpCounter--;
}
}
}
//Reset coyote counter to 0 to avoid double jumps
coyoteCounter = 0;
}
}
Commenti