2D Character Invisible To Enemies
I am working on a stealth side scrolling game for my comp. sci class and I'm somewhat of a newbie in terms of programming in Unity, so far I have the game set up so that the enemy walks in a range but I have trouble making the player character invisible when he presses the up button in order to "hide" from enemies.
So the enemy should pass through when the player is invisible (upon pressing up, of course), and if the player is caught when they are not invisible, then the game is over.
The tutorials on the site are plenty helpful but they don't really cover things like basic side scrolling games with no health system in place or stealth mechanics in a 2D game. I wasn't sure if I had to make my player character a collider trigger or whatever it is called in order to have the enemies pass through him or what.
Answer by Zoogyburger · Mar 04, 2016 at 01:36 AM
Here's an example
public BoxCollider2D mybounds;
void Start()
{
mybounds = GetComponent<BoxCollider2D> ();
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space)) {
mybounds.isTrigger = true;
}
if (Input.GetKeyDown(KeyCode.Backspace)){
mybounds.isTrigger = false;
}
}
void OnCollisionEnter2D (Collision2D other)
{
if (other.gameObject.tag == "Enemy") {
Destroy (gameObject);
}
}
}
Make sure your player has a boxcollider2D and your enemies are tagged "Enemy".
The OnCollisionEnter2D destroys the player character, correct?
EDIT: Although it didn't really do that, the two characters just continue bumping into one another.
I have it set to:
void OnCollisionEnter2D (Collision2D other) { if (other.gameObject.tag == "enemy1") { Destroy (gameObject); } }
The player character also just falls through the stage when the button is pressed as well, does making it a trigger cause that to happen and if so, what can one do to prevent that from happening?
Change the
if (other.gameObject.tag == "enemy1") {
Destroy (gameObject); } }
To
if (other.gameObject.tag == "Player") {
Destroy (other.gameObject);
And put this script on the Enemy with the $$anonymous$$ybounds in the inspector set to the player and make sure your player is tagged Player. If the Player is falling through the floor in his Rigidbody2D change the Gravity scale to be 0.