Created
February 2, 2021 13:11
-
-
Save TheCuttlefish/3473f2e43be6cff1fb255c50e58ef797 to your computer and use it in GitHub Desktop.
Jumping on walls (platformer movement)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class QuickPlayer : MonoBehaviour | |
{ | |
Rigidbody2D rb; | |
float xInput; | |
bool isGrounded; | |
bool isOnTheWall; | |
bool wallIsOnRight; | |
// Start is called before the first frame update | |
void Start() | |
{ | |
rb = GetComponent<Rigidbody2D>(); | |
} | |
// Update is called once per frame | |
void Update() | |
{ | |
if (isGrounded) | |
{ | |
//movement | |
xInput = Input.GetAxis("Horizontal") * 5; | |
rb.velocity = new Vector2(xInput, rb.velocity.y); | |
//jump | |
if( Input.GetKeyDown(KeyCode.Space)){ | |
rb.AddForce(Vector2.up * 1000f); | |
isGrounded = false; | |
} | |
} | |
if (isOnTheWall) | |
{ | |
if (Input.GetKeyDown(KeyCode.Space)) | |
{ | |
rb.constraints = RigidbodyConstraints2D.None; | |
rb.constraints = RigidbodyConstraints2D.FreezeRotation; | |
if (wallIsOnRight) | |
{ | |
rb.AddForce(new Vector2(0.5f, 0.5f) * 1000f); | |
} | |
else | |
{ | |
rb.AddForce(new Vector2(-0.5f, 0.5f) * 1000f); | |
} | |
isOnTheWall = false; | |
} | |
} | |
} | |
private void OnCollisionEnter2D(Collision2D collision) | |
{ | |
if (collision.transform.tag == "Wall") | |
{ | |
if(transform.position.x > collision.transform.position.x) | |
{ | |
wallIsOnRight = true; | |
} else | |
{ | |
wallIsOnRight = false; | |
} | |
isOnTheWall = true; | |
rb.constraints = RigidbodyConstraints2D.FreezeAll; | |
GetComponent<SpriteRenderer>().color = Color.green; | |
} | |
} | |
private void OnCollisionStay2D(Collision2D collision) | |
{ | |
if (collision.transform.tag != "Wall") | |
{ | |
isGrounded = true; | |
GetComponent<SpriteRenderer>().color = Color.red; | |
} | |
} | |
private void OnCollisionExit2D(Collision2D collision) | |
{ | |
isGrounded = false; | |
GetComponent<SpriteRenderer>().color = Color.white; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment