Eidan
Eidan

Reputation: 1

My Box Collider 2D stop working after i make it son of AttachPoint in Unity

I'm working on a game to my project in my studies and I'm trying to grab an object, I can grab it and it works good, but, when I grab it the object "enfermo" is a son of "AttachPoint" and it loses his BoxCollider2D, I don't know why and I dont find nothing in google

This is the code:

using UnityEngine;

public class PlayerGrab : MonoBehaviour
{
    public Transform attachPoint; // Punto donde se adhiere el objeto
    public float grabRange = 1f; // Rango para detectar objetos "enfermo"
    public LayerMask objectLayer; // Capa de objetos agarrables

    private Animator animator;
    private Transform currentObject; // Objeto actualmente agarrado
    private bool hasGrabbed = false;

    void Start()
    {
        animator = GetComponent<Animator>(); // Obtiene el Animator del personaje
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            TryGrab();
        }
        else if (Input.GetKeyDown(KeyCode.Q))
        {
            Release();
        }
    }

    void TryGrab()
    {
        if (hasGrabbed) return; // Si ya tiene un objeto, no hace nada

        // Buscar objetos cercanos
        Collider2D[] objects = Physics2D.OverlapCircleAll(transform.position, grabRange, objectLayer);
        foreach (Collider2D obj in objects)
        {
            if (obj.gameObject.name.StartsWith("enfermo")) // Filtra por nombre
            {
                Grab(obj.transform);
                return; // Solo agarra un objeto
            }
        }
    }

   void Grab(Transform obj)
{
    currentObject = obj;
    hasGrabbed = true;

    animator.SetBool("isGrabbing", true);

    // Guardar la posición Z original antes de adherir el objeto
    float originalZ = currentObject.position.z;

    // Adhiere el objeto al personaje
    currentObject.SetParent(attachPoint);
    currentObject.localPosition = Vector3.zero;

    // Restaurar la posición Z original
    currentObject.position = new Vector3(currentObject.position.x, currentObject.position.y, originalZ);
}


    void Release()
    {
        if (!hasGrabbed || currentObject == null) return;

        // Suelta el objeto
        currentObject.SetParent(null);

        // Cambia la animación a la normal
        animator.SetBool("isGrabbing", false);

        currentObject = null;
        hasGrabbed = false;
    }

    // Dibuja el rango de agarre en el editor
    void OnDrawGizmos()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(transform.position, grabRange);
    }
}

I search in google and I don't find nothing, I ask to ChatGPT and he sends me more code, I try it but don't works. I want when I press E close to an object my character grab it, and keep the collider of the object too.

Upvotes: 0

Views: 23

Answers (0)

Related Questions