- Home /
Collision (onTriggerEnter) stops working without a reason
Hi, im working on my first real Project in Unity. Its a topdown shooter where enemies appear the top and float downwards where i can either shoot them or collide with them to gain points/lose Hp. My Problem is, that the Collision works a few times but then it suddenly stops and no more Collision will happen.
This is for Collision between the Player and the Enemy:
void OnTriggerEnter(Collider otherObject)
{
if (otherObject.tag == "staticEnemy")
{
Debug.Log("Hit");
if ((getHealth() - 10f) > 0f)
{
// Decrease the player's health
decreaseHealth(10f);
Destroy(otherObject.gameObject);
if (getCombo() > getHighestCombo())
{
setHighestCombo(getCombo());
}
setCombo(0f);
}
else
{
Application.LoadLevel(1);
}
}
}
This is for Collision between the Projectiles and the Enemy:
void OnTriggerEnter(Collider otherObject)
{
if(otherObject.tag == "staticEnemy")
{
Destroy(otherObject.gameObject);
Destroy(gameObject);
Player.increaseScore(100f + (Player.getCombo() * 10f));
Player.increaseCombo(1);
}
}
i cant really recreate when its happening excatly, but usually it works fine for a few hits on the Enemy and losing some Hp. And at some random Point the Projectiles start flying through the Enemy the Player wont collide with the Enemy anymore. Ive already tried changing Collision Detection and a bunch of other Stuff but nothing seems to work. Im not sure if its needed, but post the full code aswell. If its not needed just skip it and thx alot already.
Player script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Player : MonoBehaviour
{
// HUD
public static Text playerStats;
public static Text currentWeaponDisplay;
public static Text rechargeStateRailgun;
// Scorescreen
public static Text scorescreen;
// Player
// upgradeable Stats
public float movementSpeed;
// Variables
enum ShipModel
{
StandardWeapon,
Railgun,
Rifle
}
public Renderer ShipDisplay;
public Material StandardWeaponDisplay;
public Material RailgunDisplay;
public Material RifleDisplay;
private ShipModel currentShip = ShipModel.StandardWeapon;
public float rotationSpeed;
public float rotationAngleSidewards;
public float rotationAngleUpwards;
private static float score = 0;
private static float health = 100;
private static float combo = 0;
private static float highestCombo = 0;
private static float missed = 0;
private static float tokens;
// Weapons
enum WeaponEquipped
{
StandardWeapon,
Railgun,
Rifle
}
private WeaponEquipped currentWeapon = WeaponEquipped.StandardWeapon;
// Standard Weapon Variables
public GameObject StandardWeaponProjectilePrefab;
// Standard Weapon upgradeable Stats
public float speedStandardWeapon;
public float cooldownStandardWeapon;
private float nextShotStandardWeapon;
// Railgun Variables
public GameObject RailgunProjectilePrefab;
// Railgun upgradeable Stats
public float speedRailgun;
public float cooldownRailgun;
private float nextShotRailgun;
// Rifle Variables
public GameObject RifleProjectilePrefab;
// Rifle upgradeable Stats
public float speedRifle;
public float cooldownRifle;
private float nextShotRifle;
// Enemy
private float spawnTimeEnemy = 1f;
private bool isSpawning;
// Use this for initialization
void Start()
{
getHUD();
updateHUD();
}
// Update is called once per frame
void Update()
{
// Player
PlayerMovement();
// Weapon
checkEquippedWeapon();
StandardWeapon();
Railgun();
Rifle();
// HUD
updateHUD();
// Ship
updateShipDisplay();
// Enemy
spawnEnemy();
}
// Player
public void PlayerMovement()
{
// Sidewards
// Movement sidewards
float amtToMoveHorizontal = Input.GetAxis("Horizontal") * movementSpeed * Time.deltaTime;
transform.Translate(Vector3.right * amtToMoveHorizontal, Space.World);
// Rotation sidewards
float amtToRotateSidewards = rotationSpeed * Time.deltaTime;
if (Input.GetAxis("Horizontal") > 0)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, -rotationAngleSidewards, 0), amtToRotateSidewards);
}
else if (Input.GetAxis("Horizontal") < 0)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, rotationAngleSidewards, 0), amtToRotateSidewards);
}
else
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.identity, amtToRotateSidewards);
}
// Border sidewards
if (transform.position.x > 8.4f)
{
transform.position = new Vector3(8.4f, transform.position.y, transform.position.z);
}
if (transform.position.x < -8.4f)
{
transform.position = new Vector3(-8.4f, transform.position.y, transform.position.z);
}
// Upwards
// Movement upwards
float amtToMoveVertical = Input.GetAxis("Vertical") * movementSpeed * Time.deltaTime;
transform.Translate(Vector3.up * amtToMoveVertical);
// Rotation upwards
float amtToRotateUpwards = rotationSpeed * Time.deltaTime;
if (Input.GetAxis("Vertical") > 0)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(rotationAngleUpwards, 0, 0), amtToRotateUpwards);
}
else if (Input.GetAxis("Vertical") < 0)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(-rotationAngleUpwards, 0, 0), amtToRotateUpwards);
}
else
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.identity, amtToRotateUpwards);
}
// Border upwards
if (transform.position.y > 0f)
{
transform.position = new Vector3(transform.position.x, 0f, transform.position.z);
}
if (transform.position.y < -4.5f)
{
transform.position = new Vector3(transform.position.x, -4.5f, transform.position.z);
}
}
// Collision
void OnTriggerEnter(Collider otherObject)
{
if (otherObject.tag == "staticEnemy")
{
Debug.Log("Hit");
if ((getHealth() - 10f) > 0f)
{
// Decrease the player's health
decreaseHealth(10f);
Destroy(otherObject.gameObject);
if (getCombo() > getHighestCombo())
{
setHighestCombo(getCombo());
}
setCombo(0f);
}
else
{
Application.LoadLevel(1);
}
}
}
// Weapons
public void StandardWeapon()
{
if (Input.GetButtonDown("Fire1") && Time.time > nextShotStandardWeapon && currentWeapon == WeaponEquipped.StandardWeapon)
{
nextShotStandardWeapon = Time.time + cooldownStandardWeapon;
// Set position
Vector3 position = new Vector3(transform.position.x,
transform.position.y + (0.6f * transform.localScale.y),
transform.position.z);
// Fire projectile
Instantiate(StandardWeaponProjectilePrefab, position, Quaternion.identity);
}
}
public void Railgun()
{
if (Input.GetButtonDown("Fire1") && Time.time > nextShotRailgun && currentWeapon == WeaponEquipped.Railgun)
{
nextShotRailgun = Time.time + cooldownRailgun;
// Set position
Vector3 position = new Vector3(transform.position.x,
transform.position.y + (0.6f * transform.localScale.y),
transform.position.z);
// Fire projectile
Instantiate(RailgunProjectilePrefab, position, Quaternion.identity);
}
}
public void Rifle()
{
if (Input.GetButtonDown("Fire1") && Time.time > nextShotRifle && currentWeapon == WeaponEquipped.Rifle)
{
nextShotRifle = Time.time + cooldownRifle;
// Set position
Vector3 position = new Vector3(transform.position.x,
transform.position.y + (0.6f * transform.localScale.y),
transform.position.z);
// Fire projectile
Instantiate(RifleProjectilePrefab, position, Quaternion.identity);
}
}
public void checkEquippedWeapon()
{
if (Input.GetKeyDown("a"))
{
currentWeapon = WeaponEquipped.StandardWeapon;
currentShip = ShipModel.StandardWeapon;
}
else if (Input.GetKeyDown("s"))
{
currentWeapon = WeaponEquipped.Railgun;
currentShip = ShipModel.Railgun;
}
else if (Input.GetKeyDown("d"))
{
currentWeapon = WeaponEquipped.Rifle;
currentShip = ShipModel.Rifle;
}
}
// Ship Display
public void updateShipDisplay()
{
ShipDisplay = GameObject.Find("Player").GetComponent<Renderer>();
ShipDisplay.enabled = true;
if (currentShip == ShipModel.StandardWeapon)
{
ShipDisplay.sharedMaterial = StandardWeaponDisplay;
}
else if (currentShip == ShipModel.Railgun)
{
ShipDisplay.sharedMaterial = RailgunDisplay;
}
else if (currentShip == ShipModel.Rifle)
{
ShipDisplay.sharedMaterial = RifleDisplay;
}
}
// HUD
public void getHUD()
{
playerStats = GameObject.Find("PlayerStats").GetComponent<Text>();
currentWeaponDisplay = GameObject.Find("currentWeapon").GetComponent<Text>();
rechargeStateRailgun = GameObject.Find("rechargeStateRailgun").GetComponent<Text>();
}
public void updateHUD()
{
// PlayerStats
playerStats.text = "Score: " + score.ToString()
+ "\nCombo: " + combo.ToString()
+ "\nHealth: " + health.ToString() + "%";
// current Weapon
if (currentWeapon == WeaponEquipped.StandardWeapon)
{
currentWeaponDisplay.text = "Standard Weapon";
}
else if (currentWeapon == WeaponEquipped.Railgun)
{
currentWeaponDisplay.text = "Railgun";
}
else if (currentWeapon == WeaponEquipped.Rifle)
{
currentWeaponDisplay.text = "Rifle";
}
// recharge state Railgun
if ((nextShotRailgun - Time.time) > 0)
{
rechargeStateRailgun.text = "Railgun ready in: " + (nextShotRailgun - Time.time).ToString();
}
else
{
rechargeStateRailgun.text = "RAILGUN READY";
}
}
// Variables
public static void setCombo(float x)
{
combo = x;
}
public static float getCombo()
{
return combo;
}
public static void increaseCombo(float x)
{
combo = combo + x;
}
public static void setHighestCombo(float x)
{
highestCombo = x;
}
public static float getHighestCombo()
{
return highestCombo;
}
public static void increaseHighestCombo(float x)
{
highestCombo = highestCombo + x;
}
public static void setScore(float x)
{
score = x;
}
public static float getScore()
{
return score;
}
public static void increaseScore(float x)
{
score = score + x;
}
public static float getHealth()
{
return health;
}
public static void decreaseHealth(float x)
{
health = health - x;
}
// Enemy
public void spawnEnemy()
{
if (!isSpawning)
{
isSpawning = true;
StartCoroutine("waitSomeSeconds");
}
}
IEnumerator waitSomeSeconds()
{
yield return new WaitForSeconds(spawnTimeEnemy);
staticEnemy.SetPositionAndSpeed();
isSpawning = false;
}
}
Enemy: using UnityEngine; using System.Collections;
public class staticEnemy : MonoBehaviour
{
public static GameObject staticEnemyPrefab;
private static float currentSpeed;
private static float minSpeed = 2f;
private static float maxSpeed = 3f;
private static float x, y, z;
private static float MinRotateSpeed = 60f;
private static float MaxRotateSpeed = 120f;
private static float MinScale = .8f;
private static float MaxScale = 2f;
private static float currentRotationSpeed;
private static float currentScaleX;
private static float currentScaleY;
private static float currentScaleZ;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
Movement();
}
public static void SetPositionAndSpeed()
{
currentRotationSpeed = Random.Range(MinRotateSpeed, MaxRotateSpeed);
currentScaleX = Random.Range(MinScale, MaxScale);
currentScaleY = Random.Range(MinScale, MaxScale);
currentScaleZ = Random.Range(MinScale, MaxScale);
// Set new speed
currentSpeed = Random.Range(minSpeed, maxSpeed);
// Set new position
x = Random.Range(-8.4f, 8.4f);
y = 4.5f;
z = 0f;
Vector3 position = new Vector3(x, y, z);
Instantiate(Resources.Load("staticEnemyPrefab"), position, Quaternion.identity);
}
public void Movement()
{
float rotationSpeed = currentRotationSpeed * Time.deltaTime;
transform.Rotate(new Vector3(-1, 0, 0) * rotationSpeed);
// Move enemy
float amtToMove = currentSpeed * Time.deltaTime;
transform.Translate(Vector3.down * amtToMove, Space.World);
if (transform.position.y <= -5.5f)
{
Destroy(gameObject);
if (Player.getCombo() > Player.getHighestCombo())
{
Player.setHighestCombo(Player.getCombo());
}
Player.setCombo(0f);
}
}
}
Projectile: using UnityEngine; using System.Collections;
public class StandardWeaponProjectile : MonoBehaviour {
private float projectileSpeed;
// Use this for initialization
void Start()
{
projectileSpeed = 10;
}
// Update is called once per frame
void Update()
{
// Move projectile
float amtToMove = projectileSpeed * Time.deltaTime;
transform.Translate(Vector3.up * amtToMove);
// Destroy projectile
if (transform.position.y > 5.2f)
{
Destroy(gameObject);
}
}
void OnTriggerEnter(Collider otherObject)
{
if(otherObject.tag == "staticEnemy")
{
Destroy(otherObject.gameObject);
Destroy(gameObject);
Player.increaseScore(100f + (Player.getCombo() * 10f));
Player.increaseCombo(1);
}
}
}
Your answer
Follow this Question
Related Questions
How to detect collision without OnCollisionEnter or OnTriggerEnter? 1 Answer
Rocket projectile damage not applied on collision (message not sent/received) 1 Answer
OnTriggerEnter function giving mixed results 1 Answer
OnTrigger event when colliders are already touching eachother 1 Answer
OnTriggerEnter - destroy (this.gameobject) if it collides with anything 2 Answers