Raycasting

Hi everyone.
First of all, this is a great course. I’m an Italian teacher and I didn’t know anything about coding before, and I feel like I’m learning a lot. During this lecture challange I tried to make my defenders fire only if there was an enemy on sight, and quit fire if there wasn’t. It took me a whole afternoon and eventually I used Raycast2d and LayerMask. It worked. I hope I don’t have messed things up too much for the next lectures. The code is here, you can use it if you want or tell me if there were other ways.

public class Defenders : MonoBehaviour {


    Animator animator;
    public GameObject proiettile;
    public bool attacca = false;
   

    // Use this for initialization
    void Start () {

        
        animator = GetComponent<Animator>();
	}

    // Update is called once per frame
    void Update()
    {

       
        if (attacca == false)
        {
            animator.SetBool("Attacca", false);
        }
        else if (attacca == true)
        {
            animator.SetBool("Attacca", true);
        }
        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, 10f, LayerMask.GetMask("Enemy"));
        if (hit.collider != null)
        {
           
                attacca = true;
        }
        else attacca = false;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log(name + " è entrato in collisione");
    }

    public void Attacking()
    {
        animator.SetBool("isAttacking", true);
    }

    public void Firing()
    {
        
      Instantiate(proiettile, transform.position,transform.rotation);
    }

}
1 Like

Privacy & Terms