- Home /
Powerup Script to make player invincible?
Title says it all. I simply want to make my player invincible after getting a powerup for a short period of time, so he can't die from touching the objects that kill him instantly. I tried to look this up on the answered questions that were asked a while back and I could not find someone who asked this question except one guy. It was in java script so it's like a whole other language to me, also his script gives his player a health bar(which mine doesn't have, I'm making an infinite runner). Anyways since this is in the answers section I don't want to make a big discussion out of it, so let's be direct please or I'll get in trouble. Here's my basic powerup script:
public class PowerupScript : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player"){
Destroy (gameObject);
}
{
}
}
}
Answer by AlucardJay · May 04, 2014 at 02:24 AM
This is basically a write-my-code question, which is impossible to answer without knowing how your health system works. So a pseudo-solution would be :
when the player hits the power-up, call a function on the player to set invincible
that function would set a boolean to true, and invoke a function to set that boolean back to false after a delay
in the health part, before deducting health there would be a check to see if the boolean is true; if not, then deduct health.
Power-up script
player.SetInvincible();
Player script
public float invincibleTime = 3.0f;
bool isInvincible = false;
public void SetInvincible()
{
isInvincible = true;
CancelInvoke( "SetDamageable" ); // in case the method has already been invoked
Invoke( "SetDamageable", invincibleTime );
}
void SetDamageable()
{
isInvincible = false;
}
// health part
if ( !isInvincible )
{
health -= whatever;
}
Sorry, I wasn't clear on my health system and how it works. $$anonymous$$y player doesn't have health, he can't die unless he touches one of the many objects spawning in front of him. Again I'm making an infinite runner, so think games like flappy bird or other endless games to where I can't die unless I touch one of the objects. I want to make my player invurnable to death and be able to pass through the objects. So now that's clear, thank you for the script but I have one error in the powerup script. Here it is:
An object reference is required to access non-static member `ControllerScript.SetInvincible()'
Here's my new powerup script:
public class PowerupScript : $$anonymous$$onoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player"){
ControllerScript.SetInvincible();
ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>(); // not sure about the syntax here...
if (playerScript)
{
// We speed up the player and then tell to stop after a few seconds
playerScript.coeffSpeedUp = 1.5f;
StartCoroutine(playerScript.StopSpeedUp());
}
Destroy (gameObject);
}
}
}
And my new Player Script:
public class ControllerScript : $$anonymous$$onoBehaviour
{
public float maxSpeed = 10f;
bool facingRight = true;
public float coeffSpeedUp = 1.0f;
public float invincibleTime = 3.0f;
bool isInvincible = false;
Animator anim;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public Layer$$anonymous$$ask whatIsGround;
public float jumpForce = 700f;
public void SetInvincible()
{
isInvincible = true;
CancelInvoke ("SetDamageable"); // in case the method has already been invoked
Invoke ("SetDamageable", invincibleTime);
}
void SetDamageable()
{
isInvincible = false;
}
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate ()
{
transform.Translate (5f * Time.deltaTime, 0f, 0f);
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
anim.SetBool ("Ground", grounded);
anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
if (!grounded)
return;
float move = Input.GetAxis ("Horizontal");
//anim.SetFloat ("Speed", $$anonymous$$athf.Abs(move));
//rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
}
void Update()
{
if (grounded && Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.Space))
{
anim.SetBool("Ground", false);
rigidbody2D.AddForce(new Vector2(0, jumpForce));
}
}
public IEnumerator StopSpeedUp() {
yield return new WaitForSeconds(1.5f); // the number corresponds to the number of seconds the speed up will be applied
coeffSpeedUp = 1.0f; // back to normal
}
}
The error is because you are trying to call the function before you have stored the component. Line 6 should be at line 10, after you store a reference to the component and can access it. Portion of the power-up script should look like this :
if (other.tag == "Player"){
ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>();
if (playerScript)
{
playerScript.SetInvincible(); // call function on playerScript to set player to invincible
// speed up coroutine, etc as you have it already
The rest depends on how your 'enemy' item affects the player. Now you have a boolean on the player that shows if it is invincible or not. However, to access this boolean from other scripts, it will need to be made public (public bool isInvincible).
So if your 'enemy' script is set up the same way, just check if the player is invincible before killing the player/moving to respawn position/etc
if (other.tag == "Player"){
ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>();
if (playerScript)
{
// check if NOT invincible
if ( !playerScript.isInvincible )
{
// explode player
// set to respawn
// other death-type stuff
}
Alright the scripts are error free, but it doesn't work sadly. $$anonymous$$aybe it's because I don't quite understand what you mean by 'enemy' script. I'm assu$$anonymous$$g you mean the obstacles in my way that kill me. I have a OnCollisionEnter2D script that I attached to my player to kill the player when he touches any of the obstacles. As for my obstacles I only have 1 script which is a spawn script. So I don't understand. Here's my Collision script:
public class OnCollisionEnter : $$anonymous$$onoBehaviour {
void Update() {
}
void OnCollisionEnter2D (Collision2D col)
{
// If the colliding gameobject is an Enemy...
if(col.gameObject.tag == "Dangerous")
{
// Find all of the colliders on the gameobject and set them all to be triggers.
Collider2D[] cols = GetComponents<Collider2D>();
foreach(Collider2D c in cols)
{
c.isTrigger = true;
}
// ... disable user Player Control script
GetComponent<ControllerScript>().enabled = false;
}
}
}
And my new updated powerup script(thanks to you):
public class PowerupScript : $$anonymous$$onoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player"){
ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>(); // not sure about the syntax here...
if (playerScript)
{
playerScript.SetInvincible(); // call function on playerScript to set player to invincible
// speed up coroutine, etc as you have it already
// check if NOT invincible
if ( !playerScript.isInvincible )
{
// explode player
// set to respawn
// other death-type stuff
// We speed up the player and then tell to stop after a few seconds
playerScript.coeffSpeedUp = 1.5f;
StartCoroutine(playerScript.StopSpeedUp());
}
Destroy (gameObject);
}
}
}
}
By the way I made my bool isInvincible to public.
Ok, I think I confused you in that last comment.
PowerUp Script
is attached to PowerUp object
is a trigger collider
finds the player script, and sets it to invincible
.
public class PowerupScript : $$anonymous$$onoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player"){
ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>();
if (playerScript)
{
// call function on playerScript to set player to invincible
playerScript.SetInvincible();
// We speed up the player and then tell to stop after a few seconds
playerScript.coeffSpeedUp = 1.5f;
StartCoroutine(playerScript.StopSpeedUp());
}
Destroy (gameObject);
}
}
}
Player Controller Script
controls the player
has functions that are called to set player to invincible, and then damageable after a delay time
.
public float invincibleTime = 3.0f;
public bool isInvincible = false;
public void SetInvincible()
{
isInvincible = true;
CancelInvoke ("SetDamageable"); // in case the method has already been invoked
Invoke ("SetDamageable", invincibleTime);
}
void SetDamageable()
{
isInvincible = false;
}
Player Collision Script
checks if a player collided with a 'Dangerous' obstacle
if player is invincible, player takes no damage
.
public class PlayerCollision : $$anonymous$$onoBehaviour {
ControllerScript player;
void Start()
{
player = GetComponent<ControllerScript>();
}
void OnCollisionEnter2D (Collision2D col)
{
// If the colliding gameobject is an Enemy...
if(col.gameObject.tag == "Dangerous")
{
// Find all of the colliders on the gameobject and set them all to be triggers.
Collider2D[] cols = GetComponents<Collider2D>();
foreach(Collider2D c in cols)
{
c.isTrigger = true;
}
// check if player is invincible
if ( player.isInvincible )
{
// keep on truckin'
}
else
{
// ... disable user Player Control script
player.enabled = false;
}
}
}
}
I still don't quite understand your setup. If the Obstacle is just going to be set to trigger anyway, why not just use trigger colliders?
The scripts aren't doing what I want them to do. It does finally affect the game but not in the way I want it to. For an example when I grab the powerup and I run into one of the obstacles in my way, I just fall through the floor like if I died, but the difference is that I fall slightly more forward then I did before(so that's how I know it affected the game). After I fall through the floor the destroyer that I placed on the bottom of the screen(it doesn't even need to be there, so don't think it has any relevance, I just haven't removed it yet) kills me and it then takes me to the game over screen(which is supposed to happen). I increased the time it takes for the invincibility to wear off but that didn't affect it at all. To answer your question about trigger colliders, I was taught to do what I do now you see. I watched many different Youtube tutorials from many different people(so the methods are all different). I know some methods aren't the best(the colliders for example) but that's all I know. I'll check out trigger colliders while waiting for your response and see if that works for me. Thanks again for the scripts btw.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Help! How can I get my power up script to work? 1 Answer
Animation spins wildly after completed 0 Answers
hide object start script 4 Answers