- Home /
Move object to some random position once it gets in collision
I need my object to move once it gets in collision with another object, denoted and tagged as enemy. I am having this js script, however it won't work, once I get it on my object which I tend to be moving. What may be the cause of this issue? Thanks in advance for your answers.
private var enemyTag: String = "Enemy";
function OnCollisionEnter(collision : Collision){
if (collision.gameObject.tag == enemyTag){
this.transform.position = Vector3(Random.Range(0, 100),0, Random.Range(0, 100));
}
}
function OnCollisionEnter(collision : Collision){
Debug.Log( "collision.gameObject.tag = " + collision.gameObject.tag );
// if .... the rest
what does this print out in the console ?
I have tried it before, and it doesn't detect collision at all even though I have set up sphere collider and set trigger on true.
Well, that would be the problem then. This should work for any collision. As soon as it happens, the script is saying "hey, what did I hit?", so if there is no debug in the console then the colliders are not set up correctly.
Oh, if you are using a trigger, then you want OnTriggerEnter : http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnTriggerEnter.html
Note that trigger events are only sent if one of the colliders also has a rigidbody attached.
For non-trigger collision : http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionEnter.html
Note that collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached.
You need to work on your objects, get that debug printing in the console!
Yes, I know for those scenarios, however this isn't working ...
Dude, its simple. You have a collider, and you want to check for collisions. Either you are checking for collision, or trigger. The rules for both are above. For either to work, you need to have a rigidbody attached. It's all there ....
Watch : http://www.unity3dstudent.com/2010/07/beginner-b01-basic-collision-detection/
and : http://www.unity3dstudent.com/2010/07/beginner-b13-trigger-collision-detection/
then watch them all (start at the bottom and work up) : http://www.unity3dstudent.com/category/modules/
Answer by Ben Ezard · Dec 27, 2012 at 01:57 PM
You should use the "Equals" method when comparing strings, so private var enemyTag: String = "Enemy";
function OnCollisionEnter(collision : Collision){
if (collision.gameObject.tag.Equals(enemyTag)){
this.transform.position = Vector3(Random.Range(0, 100),0, Random.Range(0, 100));
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613090005im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Destroy All of One One object on collision 1 Answer
OnCollision Script... 2 Answers
Turning an object into a RigidBody and applying a force on it... 2 Answers
A node in a childnode? 1 Answer