Here’s a script that allows me to activate a door when E is pressed. I’d like to change this script so that the door activates after a collision with a ball fired by the player. Can you help me? Thank you
kind regard,
There are two scripts, the door and the button. Here’s the one for the button.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class levier : MonoBehaviour {
public GameObject porte;
private bool inTrigger;
void Update() {
if (inTrigger) {
if (Input.GetKeyDown(KeyCode.E)) {
porte.GetComponent<porte>().ouverture();
GetComponent<Animator>().SetTrigger("activation");
}
}
}
void OnTriggerEnter2D(Collider2D truc) {
if (truc.tag == "Player") {
inTrigger = true;
}
}
void OnTriggerExit2D(Collider2D truc) {
if (truc.tag == "Player") {
inTrigger = false;
}
}
}
So you are on the right path for sure. Currently, if the Player enters the trigger area, it sets a bool called inTrigger to true. Then in update you are checking if inTrigger is true, if it is then you move on to check for Input of the E key. So instead of checking for the E key, you could replace that with checking for another bool, like “ballHasHitDoor” or something. Then you set up the logic so ballHasHitDoor becomes true when the ball collides with the door. Essentially the same logic but with a different bool and different object.
I’ll let you figure out the rest. Come back if you are still having issues.
Of course. So on your door object, create a new class (script) called Door or something and attach it to the object in the scene. Add the OnTriggerEnter2D function to this class. Create a bool variable like “beenHit” or “hitByProjectile” or whatever. Then assign a tag to the ball/projectile that makes sense.
In the OnTriggerEnter2D function on your door class, you check for other object’s tag, just like you do in your Levier class above. But this time it will be other.tag == “Projectile” or whatever you tagged your ball as, instead of player. You then set the hitByProjectile bool to true.
From here there are a couple ways, some better than others, but to keep it simple and get it working i suggest the following. Make a reference to the Door class on your Levier class. Then replace the Input.GetKey line with
if(doorClass.hitByProjectile == true)
{
do the animator set trigger stuff you are already doing
}
That should get your pretty well started. If you do that and it is still not working, please post more of your code