I'm working on a school project, and I need help with this trigger2dstay thing. I'm trying to make it were when my player's collider tag enters the triggers collider, an image pops up which works, but I'm also trying to make it were when the play does the same thing and presses E, it will trigger a animation, but when my 2d player walks in the trigger and presses E, nothing happens. pressing E only works when you are moving and pressing it, and not staying still.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class buttonele : MonoBehaviour
{
public GameObject Obje;
public GameObject blockers;
public GameObject eledoorn;
public GameObject eledormation;
bool Unlock;
// Start is called before the first frame update
void Start()
{
Obje.SetActive(false);
eledormation.SetActive(true);
Unlock = false;
}
void OnTriggerStay2D(Collider2D other)
{
if (other.tag == "Player")
{
Unlock = true;
Obje.SetActive(true);
}
if (Unlock == true && Input.GetKeyDown(KeyCode.E))
{
Destroy(blockers);
Destroy(eledoorn);
eledormation.GetComponent<Animator>().Play("eleopen");
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player")
{
Obje.SetActive(false);
}
}
}
CodePudding user response:
The following code means that your player enters another player's collider, do you really want that?
if (other.tag == "Player")
To solve this problem, test the logic of the code. If you want your player to be able to use the E key by entering a certain area, you need to enter the tag of that place in this field. If you want the boxes to open, give them a special tag (Item
for e.g) and change the code as follows.
if (other.CompareTag("Item"))
{
// do something..
}
CodePudding user response:
you can change the script method to "OnTriggerEnter2D(Collider2D collision)".
private void OnTriggerEnter2D(Collider2D collision)
{
if (other.tag == "Player")
{
Unlock = true;
Obje.SetActive(true);
}
if (Unlock == true && Input.GetKeyDown(KeyCode.E))
{
Destroy(blockers);
Destroy(eledoorn);
eledormation.GetComponent<Animator>().Play("eleopen");
}
}
The collision components used in 2D projects and 3D projects in Unity are different, and the related classes and methods are also different. If two objects in the 2D project want to collide, first hang the Box Collider2D component for the double hair, check the Is Trigger property according to the requirements, then hang the RigidBody2D component for at least one of them, set the body type to kinematic.