- Home /
My character can no longer jump and my enemies do not turn direction. Still new to Unity.
My player and Enemy have a Superclass script name "Character" So here is what I have for my Character Script. Ignore the comment lines those were some codes I wasn't sure if I was going to use.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public abstract class Character : MonoBehaviour {
//protected hides it from the enemy script or other scripts accessing this one
[SerializeField]
protected Transform bulletPos;
[SerializeField]
protected float movementSpeed;
protected bool facingRight;//indicates if the player is facing right
[SerializeField]
private GameObject bulletPrefab;
[SerializeField]
protected int health;
/*[SerializeField]
protected EdgeCollider2D SwordCollider;*/
[SerializeField]
private List<string> damageSources;
public abstract bool IsDead { get; }
public bool Attack { get; set; }
public bool TakingDamage { get; set; }
public Animator MyAnimator { get; private set; }
public virtual void Start ()
{
facingRight = true;
MyAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
}
public abstract IEnumerator TakeDamage();
public abstract void Death();
public void ChangeDirection()
{
facingRight = !facingRight;
transform.eulerAngles = new Vector3(0, 180, 0);
//Vector3(transform.localScale.x * -1f, transform.localScale.y, transform.localScale.z);
//transform.localScale = new Vector3(transform.localScale.x * -1, 1, 1);
}
public virtual void ShootBullet(int value)
{
if (facingRight)
{
GameObject tmp = (GameObject)Instantiate(bulletPrefab, bulletPos.position, Quaternion.identity); //Euler(new Vector3(0, 0, -90)))
tmp.GetComponent<Bullet>().Initialize(Vector2.right);
}
else
{
GameObject tmp = (GameObject)Instantiate(bulletPrefab, bulletPos.position, Quaternion.Euler(new Vector3(0, 0, 180)));
tmp.GetComponent<Bullet>().Initialize(Vector2.left);
}
}
/*public void MeleeAttack()
{
SwordCollider.enabled = !SwordCollider.enabled;
}*/
public virtual void OnTriggerEnter2D(Collider2D other)
{
if (damageSources.Contains(other.tag))
{
StartCoroutine(TakeDamage());
}
}
}
Here is my Enemy Script.
using System; using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Enemy : Character { private IEnemyState currentState;
public GameObject Target { get; set; }
public override bool IsDead
{
get
{
return health <= 0;
}
}
private Vector3 startPos;
[SerializeField]
private Transform leftEdge;
[SerializeField]
private Transform rightEdge;
// Use this for initialization
public override void Start ()
{
this.startPos = transform.position;
base.Start();
Player.Instance.Dead += new DeadEventHandler(RemoveTarget);
ChangeState(new IdleState());
}
// Update is called once per frame
void Update ()
{
if (!IsDead)
{
if (!TakingDamage)
{
currentState.Execute();
}
LookAtTarget();
}
}
private void LookAtTarget()
{
if (Target != null)
{
float xDir = Target.transform.position.x - transform.position.x;
if (xDir < 0 && facingRight || xDir > 0 && !facingRight)
{
ChangeDirection();
}
}
}
public void RemoveTarget()
{
Target = null;
ChangeState(new PatrolState());
}
public void ChangeState(IEnemyState newState)
{
if (currentState != null)
{
currentState.Exit();
}
currentState = newState;
currentState.Enter(this);
}
public void Move()
{
if (!Attack)
{
if ((GetDirection().x > 0 && transform.position.x < rightEdge.position.x) || (GetDirection().x < 0 && transform.position.x > leftEdge.position.x))
{
MyAnimator.SetFloat("speed", 1);
transform.Translate(GetDirection() * (movementSpeed * Time.deltaTime), Space.World);
}
}
else if (currentState is PatrolState)
{
ChangeDirection();
}
}
public Vector2 GetDirection()
{
return facingRight ? Vector2.right : Vector2.left;
}
public override void OnTriggerEnter2D(Collider2D other)
{
base.OnTriggerEnter2D(other);
currentState.OnTriggerEnter(other);
}
public override IEnumerator TakeDamage()
{
health -= 10;
if (!IsDead)
{
MyAnimator.SetTrigger("damage");
}
else
{
MyAnimator.SetTrigger("die");
yield return null;
}
}
public override void Death()
{
MyAnimator.SetTrigger("idle");
MyAnimator.ResetTrigger("die");
transform.position = startPos;
Destroy(gameObject);
}
}
Here is my Player Script.
using System; using System.Collections; using System.Collections.Generic; using UnityEngine;
public delegate void DeadEventHandler();
public class Player : Character //this inherits script from a character. If you use enemy your char will be an enemy {
private static Player instance;
public event DeadEventHandler Dead;
public static Player Instance
{
get
{
if (instance == null)
{
instance = GameObject.FindObjectOfType<Player>();
}
return instance;
}
}
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
[SerializeField]
private LayerMask whatIsGround;
[SerializeField]
private bool airControl;
private bool immortal = false;
[SerializeField]
private float immortalTime;
private SpriteRenderer spriteRenderer;
[SerializeField]
private float jumpForce;
[SerializeField]
protected EdgeCollider2D swordCollider;
public Rigidbody2D MyRigidbody { get; set; }
public bool Slide { get; set; }
public bool Jump { get; set; }
public bool OnGround { get; set; }
private Vector2 startPos;
public Player Instance1
{
get
{
return instance;
}
set
{
instance = value;
}
}
public override bool IsDead
{
get
{
if (health <= 0)
{
OnDead();
}
return health <= 0;
}
}
// Use this for initialization
public override void Start()
{
base.Start();
startPos = transform.position;
spriteRenderer = GetComponent<SpriteRenderer>();
MyRigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
if (!TakingDamage && !IsDead)
{
if (transform.position.y <= -14f)
{
Death();
}
}
HandleInput();
}
// Update is called once per frame
void FixedUpdate()
{
if (!TakingDamage && !IsDead)
{
float horizontal = Input.GetAxis("Horizontal");//we are writing horizontal in here
//because in Project Settings>Input>Get Axis>Horizontal shows that it is X axis
OnGround = IsGrounded();
HandleMovement(horizontal);
HandleLayers();
Flip(horizontal);
}
}
public void OnDead()
{
if (Dead != null)
{
Dead();
}
}
//this defines the parameter
private void HandleMovement(float horizontal)
{
if (MyRigidbody.velocity.y < 0)
{
MyAnimator.SetBool("land", true);
}
if (!Attack && !Slide && (OnGround || airControl))
{
MyRigidbody.velocity = new Vector2(horizontal * movementSpeed, MyRigidbody.velocity.y);
}
if (Jump && MyRigidbody.velocity.y == 0)
{
MyRigidbody.AddForce(new Vector2(0, jumpForce));
}
MyAnimator.SetFloat("speed", Mathf.Abs(horizontal));
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
MyAnimator.SetTrigger("jump");
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
MyAnimator.SetTrigger("attack");
}
if (Input.GetKeyDown(KeyCode.F))
{
MyAnimator.SetTrigger("shoot");
//ShootBullet(0);
}
}
private void Flip(float horizontal)
{ //facing right is true or false character will flip
if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
//ChangeDirection();
}
}
private bool IsGrounded()
{ //this check if we are standing on the ground if its less or = to 0
if (MyRigidbody.velocity.y <= 0)
{
foreach (Transform point in groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
return true;
}
}
}
}
return false;
}
private void HandleLayers()
{
if (!OnGround)
{
MyAnimator.SetLayerWeight(1, 1);
}
else
{
MyAnimator.SetLayerWeight(1, 0);
}
}
public override void ShootBullet(int value)
{
if (!OnGround && value == 1 || OnGround && value == 0)
{
base.ShootBullet(value);
}
}
public void MeleeAttack()
{
swordCollider.enabled = !swordCollider.enabled;
}
private IEnumerator IndicateImmortal()
{
while (immortal)
{
spriteRenderer.enabled = false;
yield return new WaitForSeconds(.1f);
spriteRenderer.enabled = true;
yield return new WaitForSeconds(.1f);
}
}
public override IEnumerator TakeDamage()
{
if (!immortal)
{
health -= 10;
if (!IsDead)
{
MyAnimator.SetTrigger("damage");
immortal = true;
StartCoroutine(IndicateImmortal());
yield return new WaitForSeconds(immortalTime);
immortal = false;
}
else
{
MyAnimator.SetLayerWeight(1, 0);
MyAnimator.SetTrigger("die");
}
}
}
public override void Death()
{
MyRigidbody.velocity = Vector2.zero;
MyAnimator.SetTrigger("idle");
health = 50;
transform.position = startPos;
}
}