Skip to content

Instantly share code, notes, and snippets.

@andrewlaskey
Created March 14, 2020 20:58
Show Gist options
  • Save andrewlaskey/2b23263c9bb563279c9e39f9b9f27c04 to your computer and use it in GitHub Desktop.
Save andrewlaskey/2b23263c9bb563279c9e39f9b9f27c04 to your computer and use it in GitHub Desktop.
Basic 2D player controller with long jump for Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
private Rigidbody2D rb;
private float moveInput;
public float speed;
public float jumpForce;
public float jumpTime;
private bool isJumping;
private float jumpTimeCounter;
private bool isTouching;
private Collider2D coll;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<Collider2D>();
}
private void FixedUpdate()
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
private void Update()
{
if (Physics2D.IsTouchingLayers(coll) && Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
} else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment