- Home /
Adding "Air" on a collision
So right now I have the player swimming around and I'd like that when he collides with the surface his "air" refills. It seems that when he collides with the "surface" he looses it all and I beleive it might be from me trying to find the difference between the amount he has, and the amount he needs to fill up. Thanks!
using UnityEngine;
using System.Collections;
public class Meter : MonoBehaviour {
public float air = 10;
public float maxAir = 10;
public float airBurnRate = 1f;
private Player player;
// Update is called once per frame
void Update () {
if (air > 0) {
air -= Time.deltaTime * airBurnRate;
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Surface") {
Debug.Log ("AIR!!!");
var addair = air - 10; // Find the difference
air = air + addair; // Add the difference to fill up
}
}
}
Answer by DFledermaus · Oct 21, 2014 at 09:08 PM
The problem is line 23:
var addair = air - 10;
You're using 10 instead of maxair (which is 10, but that will cause problems if you ever decide to change maxair) but you also have them in the wrong order.
Replace that line with:
var addair = maxair - air;
Answer by mwbranna · Oct 21, 2014 at 09:06 PM
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Surface") {
air = maxAir; //Is this what you are trying to do?
}
}
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Setting an Object to a variable after collision 0 Answers
Variables from one script to another. 3 Answers
How to access Particle System Collision to change at runtime 1 Answer
Multiple Cars not working 1 Answer