Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by jt4life · Jul 31, 2017 at 05:07 AM · scripting beginnerjumpdirection

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;
 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

72 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Why doesn't my object move left? 1 Answer

2D jump script doesn't work properly. 1 Answer

How do I get the sound effect to continue playing? 1 Answer

I made Infinite jump Fix Script By Myself But I Want You Guys To Take Look at My Script... 0 Answers

How to change the gravity scale of the rigidbody 2d back to it's default value after player lands to the ground from jump 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges