I have Power Ups in my game that randomly spawn. My player can shoot objects like lasers and such. I’ve used C# scripting to tell the projectiles to ignore the Power Ups. I’ve even placed them on different “layers”. Yet, there are times when the two objects will still have an effect on each other.
Example 1 - Power Up spawns while enemy laser is already moving. Enemy laser and Power Up collide causing the laser to lazily move in a random direction determined by physics. Yet, subsequent lasers correctly ignore the Power Up.
Example 2- Even as the subsequent laser ignore the Power Up, they still slow down when flying through the power up. If I tested this by lining up 3 Power Ups in a row and had an enemy laser fly through them, the laser would “ignore” but clearly be effected by friction and slow down to an almost dead stop upon exiting the last Power Up.
This is the script for the lasers that is instructing them to ignore certain objects in certain layers:
When you do this line in Power Ups? Maybe the GetComponent is too slow, and the line is not called when effects in game? Try to swap GetComponent on awake or public and assigned in editor, maybe change something
This is the entirety of the script for my power ups in game:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUpBehavior : MonoBehaviour {
private float puRotation;
void Start ()
{
puRotation = 125.0f;
}
void Update ()
{
GetComponent<Rigidbody>().rotation = Quaternion.Euler(90.0f, puRotation*Time.time, 0.0f);
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
if (gameObject.tag == "WeaponPowerUp")
AudioController.WpnPowerUp();
if (gameObject.tag == "ShieldPowerUp" || gameObject.tag == "LifePowerUp")
AudioController.PowerUp();
Destroy(gameObject);
}
else
Physics.IgnoreCollision(collision.collider, GetComponent<Collider>());
}
}
However, I did try to move the IgnoreCollision above the rest of the statement like so:
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag != "Player")
Physics.IgnoreCollision(collision.collider, GetComponent<Collider>());
else if (collision.gameObject.tag == "Player")
{
if (gameObject.tag == "WeaponPowerUp")
AudioController.WpnPowerUp();
if (gameObject.tag == "ShieldPowerUp" || gameObject.tag == "LifePowerUp")
AudioController.PowerUp();
Destroy(gameObject);
}
}
Still no success.
However, your answer got me thinking. The OnCollisionEnter function requires the two objects to have already collided with each other for it to kick in. At that point physics has already happened. Is there a way to simply get the object to ignore each others’ existence before the collision?
Mino92, I’m going to give you credit for helping solve this. As I was looking into the layer collision matrix I realized that at no point in my scripts did I tell the Enemy Lasers and the Power Ups (both on different layers) to ignore each other. That was my issue…-_-