RaycastHit2D Unity

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

public class MyRayCast : MonoBehaviour
{
    [SerializeField] Transform aim;

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            FireRaycast();
        }
    }

    void FireRaycast()
    {
        RaycastHit2D hit = Physics2D.Raycast(aim.position, transform.right, 5f);
        Debug.DrawRay(aim.position, transform.TransformDirection(Vector2.right) * 5, Color.red, 2f);
        if (hit)
        {
            //if(hit.transform.TryGetComponent<Target>(out Target tr))
            //{
            //    tr.OnShoot(hit.transform.position - transform.position);
            //}
            Debug.Log(hit.collider.name);
        }
    }
}
// Raycast za pomocą pozycji myszy

using UnityEngine;

public class MyRayCast : MonoBehaviour
{
    [SerializeField] LayerMask mask;
    Camera cam;

    void Start() => cam = Camera.main;

    void Update()
    {
        if (Input.GetButtonDown("Fire1")) FireRaycast();
    }

    void FireRaycast()
    {
        Vector2 worldPoint = cam.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero, 100f, mask);
        if (hit)
        {
            Debug.Log(hit.collider.name);
        }
    }
}

Scroll to Top