Skip to content

Instantly share code, notes, and snippets.

@badrshs
Created August 19, 2018 04:11
Show Gist options
  • Save badrshs/cf767b661dda9d6f957bcabc44b14967 to your computer and use it in GitHub Desktop.
Save badrshs/cf767b661dda9d6f957bcabc44b14967 to your computer and use it in GitHub Desktop.
player controller with extra Jump feature + flip function
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private int extraJump;
public int extraJumpValue;
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rigidbody2;
private bool facingRight = true;
public bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask WhatIsGround;
void Start()
{
extraJump = extraJumpValue;
rigidbody2 = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius,WhatIsGround);
moveInput = Input.GetAxis("Horizontal");
rigidbody2.velocity =new Vector2(moveInput*speed,rigidbody2.velocity.y);
if(facingRight==true&&moveInput<0)
Flip();
if(facingRight==false&&moveInput>0)
Flip();
}
void Update()
{
if (isGrounded == true)
{
extraJump = extraJumpValue;
}
if ((Input.GetKeyDown(KeyCode.UpArrow)|| Input.GetKeyDown(KeyCode.W)|| Input.GetKeyDown(KeyCode.Space)) &&extraJump>0)
{
rigidbody2.velocity = Vector2.up*jumpForce;
extraJump--;
}else if ((Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.Space)) && extraJump == 0&&isGrounded==true)
{
rigidbody2.velocity = Vector2.up * jumpForce;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 scaller = transform.localScale;
scaller.x *= -1;
transform.localScale = scaller;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment