Im New and i have big problem with my 2d platformer, please help me

Updated on November 16, 2018 in [A] 2D
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on November 13, 2018

Hello, Ive got problem with my script. Im trying to make my player Hide from enemy on trigger only, Script that i made (Im ultra begginer) works only sometimes (about 2 times for 10 attempts). Why? Heres my code:

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Player : MonoBehaviour {

  1. public int health = 100;
  2. bool hide = false;
  3. public GameObject zly;
  4. public Collider2D objectCollider;
  5. public Collider2D anotherCollider;
  6. void Start()
  7. {
  8. objectCollider = GameObject.FindGameObjectWithTag("Player").GetComponent<BoxCollider2D>();
  9. anotherCollider = GameObject.FindGameObjectWithTag("Shelter").GetComponent<BoxCollider2D>();
  10. }
  11. public void TakeDamage(int damage)
  12. {
  13. health -= damage;
  14. if (health <= 0)
  15. {
  16. Die();
  17. }
  18. }
  19. public void Update()
  20. {
  21. if (objectCollider.IsTouching(anotherCollider))
  22. {
  23. if (Input.GetButtonDown("Hide"))
  24. {
  25. hide = true;
  26. Physics2D.IgnoreCollision(zly.GetComponent<BoxCollider2D>(), this.GetComponent<BoxCollider2D>(), true);
  27. Physics2D.IgnoreCollision(zly.GetComponent<BoxCollider2D>(), this.GetComponent<CircleCollider2D>(), true);
  28. Debug.Log("Hide", gameObject);
  29. }
  30. }
  31. if (Input.GetButtonUp("Hide"))
  32. {
  33. hide = false;
  34. Physics2D.IgnoreCollision(zly.GetComponent<BoxCollider2D>(), this.GetComponent<BoxCollider2D>(), false);
  35. Physics2D.IgnoreCollision(zly.GetComponent<BoxCollider2D>(), this.GetComponent<CircleCollider2D>(), false);
  36. }
  37. }
  38. void OnCollisionEnter2D (Collision2D col)
  39. {
  40. if (col.gameObject.name == "Enemy")
  41. {
  42. if (hide == false)
  43. {
  44. Die();
  45. }
  46. else if (hide == true)
  47. {
  48. }
  49. }
  50. }
  51. void Die()
  52. {
  53. Destroy(gameObject);
  54. }
  • Liked by
Reply
0 on November 16, 2018

Why do you want to ignore the collision? You already have the boolean hide and used it nearly properly. So you can remove those lines and moreover you should use “Tags” instead of the gameobject name itself. So create a tag of “Enemy” and then change it in the code as follows.

void OnCollisionEnter2D (Collision2D col)
{
if (col.tag == "Enemy")
{
if (hide)
{
Die();
}
else
{
}
}
}

 

I also made this code much shorter, cause hide is a boolean.

  • Liked by
Reply
Cancel