- Home /
Collition help
I've scripted a object so when one button is pressed it moves across the screen in one direction and when another button is pressed it does the opposite. However the Script is on the Button and not on the object so I can't stop it from going thought the walls using the "OnCollisionEnter" function in the script. Is there anyway to control the object when it hits a wall without "OnCollisionEnter"?
Answer by kromenak · Feb 13, 2013 at 08:08 PM
There are two solutions I can think of here:
First, you could create a separate script that you add to the object itself. Then, you can have an OnCollisionEnter on the object and, when it hits a wall, force it to change direction. That way, your button would only care about changing direction, and the object itself can worry about dealing with walls.
The second option is to use the FixedUpdate on the button script to perform a raycast from the object location in the direction it is moving. You could then possibly use the raycast results to determine if the object has a wall right in front of him. If he does, you could then make him turn around. See http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
Personally, I prefer the first option because it splits clear responsibilities between scripts, and it also handles hitting the wall in an event-based way rather than polling every frame.
I'll go with the first option, however how would I calculate what direction the object is co$$anonymous$$g from so I can counteract that in the script?
I guess it depends on how you are moving the object; if you are moving it along a particular axis, you can use transform.Rotate to rotate around that axis 180 degrees and move in the opposite direction. Or if you are using a vector of some sort to specify the movement direction, you can get the opposite movement direction by multiplying the movement vector by -1.
Your answer
![](https://koobas.hobune.stream/wayback/20220613092639im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Help in solving mistake in my code 1 Answer
Know if there is Collisions on my boxCollider 1 Answer
Unity not recognising Destroy() 2 Answers
scripts for collision not working 0 Answers
JavaScript - Reset Characters Position 2 Answers