Detect if an object is bigger or smaller than you when you collide with it.
Hello everyone !
I need help with a script that basically detects if the object the player collides with is bigger or smaller than the player.
If the object is bigger, the player dies. if the object is smaller, the player eats it.
C# is what I'm working with, please guys any help would really help me out.
Answer by brunocoimbra · Jan 06, 2016 at 01:53 AM
Assuming you are using boxColliders, you can use:
private BoxCollider boxCollider;
private float volume;
void Start()
{
boxCollider = GetComponent<BoxCollider >();
Vector3 geometry = boxCollider.bounds.size;
volume = geometry.x * geometry.y * geometry.z;
}
void OnTriggerEnter(Collider otherCollider)
{
Vector3 geometry = otherCollider.bounds.size;
float otherVolume = geometry.x * geometry.y * geometry.z;
if (volume < otherVolume)
{
// die;
}
else if (volume > otherVolume)
{
// eat;
}
}
There is ways to calculate volume for spheres and cillinders (and other shapes) too, google is your friend here. Another option would be play around with the Collider.bounds to see what fits to you.
Also, the Mesh component also has a bounds.size, but I would say to you stick with colliders, as handling collisions will be easier.
@ brunocroimbra
Thank you so much for the fast response ! Hey I hate to be a pain, but there seems to be something wrong with the code you submitted. I'm getting errors . =(
Error # 1: Assets/Scripts/sizeDetect.cs(12,9): error CS0266: Cannot implicitly convert type UnityEngine.Collider' to
UnityEngine.BoxCollider'. An explicit conversion exists (are you missing a cast?)
Error # 2:
Assets/Scripts/sizeDetect.cs(13,40): error CS1061: Type UnityEngine.BoxCollider' does not contain a definition for
Bounds' and no extension method Bounds' of type
UnityEngine.BoxCollider' could be found (are you missing a using directive or an assembly reference?)
Error # 3:
Assets/Scripts/sizeDetect.cs(19,42): error CS1061: Type UnityEngine.Collider' does not contain a definition for
Bounds' and no extension method Bounds' of type
UnityEngine.Collider' could be found (are you missing a using directive or an assembly reference?)
Sorry about that, I didn't tested the code, but already edited my answer with the corrections.
The Error#1 was because of "GetComponent()" that should be "GetComponent()". The Error#2 and Error#3 was because "Bounds" were meant to be "bounds" (Bounds is the type).
Thank you so much for your help ! This will work for me, I'll be able to build on to this to fit my game ! =) Thank you brunocoimbra !
Your answer
Follow this Question
Related Questions
Check for collision ONCE 0 Answers
Need some help programming basic AI movement 0 Answers
Get list of enemies in range 1 Answer
how to destroy an object once you collide with it the second time? 0 Answers