- Home /
How to make collision check if other collider has component
Hi! I've quite recently started learning javascript and I still have quite some trouble with it. I'm currently working on a RPG-game and have started a test scene, it contains:
EnemyCube <- Atm static cube, with a box collider and a script that senses if mouse is over it and makes it change colors aswell as mouse cursor-texture. If mousebutton is pressed when it's hovering over it the variable "selected" is changed from 0 to 1.
PlayerCube <- Moves to where the mouse is clicking, it has a box collider aswell as an empty child-object with a sphere collider ("RangeCollider"), I want the rangecollider to kick in when it senses another Collision, I want it to check if the other colliders object is tagged with the tag "monster"
In case the tag is "monster" I want it to read if the "selected" variable is 1 in the EnemyCubes script, in that case I also want the PlayerCube to call "function isInCombat()"
My problem is the part where I want my "RangeCollider" to look if the other collider has the EnemyScript and if that scripts "selected" variable is set to 1. I'm kinda clueless.
Your question is well-presented and the concepts clearly explained, but it always helps to include script examples so we have something to work with!
Answer by · Oct 08, 2010 at 09:12 AM
This is just a quick-and-dirty untested approach, but hopefully it explains the concepts.
function OnCollisionEnter ( hit : Collision ) { if ( hit.gameObject.tag == "monster" ) // did we collide with a gameObject tagged 'monster' { var monster = hit.gameObject.GetComponent(EnemyCube); // store the EnemyScript to a local variable
if ( monster ) // if we found an EnemyScript on the monster
{
if ( monster.selected == 1 ) // if the monster's selected value is 1
{
// Do your thing
}
}
} }
By the sounds of things, all you were missing was the GetComponent call to find the EnemyScript. If you're unable to work this into your code, post what you have and I can adapt it to your approach.
*Err. sorry for double-commenting but in case another beginner has the same problem in the future keep this in $$anonymous$$d if you haven't thought about it already:
I had to move my mouse cursor to the ignore_ray layer (could probably work with some coding with physics_ignore aswell I guess?)
If I didn't do that the mouse couldn't reach the enemy-Object 'cause the "RangeCollider"-collider I had on the player was blocking it. I'm not sure how, I guess the mouse should ignore the enemy collider aswell? but meh, it worked for me :D