2D Platformer Code

PHOTO EMBED

Sat Mar 12 2022 19:04:51 GMT+0000 (Coordinated Universal Time)

Saved by @BryanJ22

using UnityEngine;
using System.Collections;

public class playerController : MonoBehaviour 
{
	public float speed = 8;
	public float jumpForce = 18;
	public float bounceAmount = 15;
	public GameObject currentEnemy;
	public GameObject playerCanvas;
	public GameObject experience;

	private float moveVelocity = 0;
	private bool grounded = false;
	private bool hitEnemyTop = false;

	[HideInInspector]
	public bool hitEnemy = false;

	void Update () 
	{
		if(transform.parent.GetComponent<knockBack>().goKnockBack == false)
		{
			if (Input.GetKeyDown (KeyCode.W)) 
			{
				if(grounded)
				{
					transform.parent.GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, jumpForce);
				}
			}

			if (Input.GetKey (KeyCode.A)) 
			{
				moveVelocity = -speed;
			}

			else if (Input.GetKey (KeyCode.D)) 
			{
				moveVelocity = speed;
			}

			else
            {
				moveVelocity = 0;
			}

			transform.parent.GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, transform.parent.GetComponent<Rigidbody2D>().velocity.y);
		}

		if (hitEnemyTop) 
		{
			if(currentEnemy.GetComponent<SpriteRenderer>().color == transform.parent.GetComponent<SpriteRenderer>().color)
			{
				transform.parent.GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, bounceAmount);
				currentEnemy.GetComponentInChildren<enemyHealth>().removeHealth();
				hitEnemyTop = false;
			}

			else
			{
				playerCanvas.GetComponentInChildren<playerHealth>().removeHealth();
				startKnockBack();
				hitEnemyTop = false;
			}
		}

		if (!hitEnemyTop && hitEnemy) 
		{
			playerCanvas.GetComponentInChildren<playerHealth>().removeHealth();
			startKnockBack();
			hitEnemy = false;
		}

		if(currentEnemy != null)
		{
			if(currentEnemy.GetComponentInChildren<enemyHealth>().health.fillAmount <= 0)
			{
				experience.GetComponent<experienceCounter>().addExperience();
				Destroy(currentEnemy);
			}
		}
	}

	void startKnockBack()
	{
		if(transform.position.x <= currentEnemy.transform.position.x)
		{
			transform.parent.GetComponent<knockBack>().knockFromRight = false;
		}
		
		else 
		{
			transform.parent.GetComponent<knockBack>().knockFromRight = true;
		}
		
		transform.parent.GetComponent<knockBack>().create_knockBack();
	}
	
	void OnTriggerEnter2D(Collider2D other)
	{
		if (other.tag == "ground") 
		{
			grounded = true;
		}

		if (other.tag == "enemyTop") 
		{
			currentEnemy = other.gameObject;
			hitEnemyTop = true;
		}
	}

	void OnTriggerExit2D(Collider2D other)
	{
		if (other.tag == "ground") 
		{
			grounded = false;
		}
	}
}
content_copyCOPY