Having a OnTriggerEnter make another gameobject Add Force in UnityScript.
Using javascript, I was experimenting with OnTrigger functions with a trigger game object, I thought about triggering another gameobject to add force. Problem is, I don't understand how it would work with a OnTriggerEnter function after adding a "if" statement for identifying a tag or gameobject to detect.
How does one achieve this when using two separate OnTriggers like Enter and Exit.
Does that mean I have to use a function update
if I don't create another separate script for the game object that has add force?
Thanks.
Answer by ComradeVanti · Apr 13, 2016 at 09:02 AM
So I dont really know Javascript.. so imma just answer in C#.. sorry. But it is pretty similar so.. you will be fine :)
If I understood you correctly you want to add force to an object when it enters a trigger. Here is what you wanna do:
void OnTriggerEnter(Collider coll){
if(coll.tag == "YourTag")
coll.getComponent<Rigidbody>().addForce(yourVector);
}
Sorry its not formatted... wrote it on the fly :)
So... does this help? :D
@Brullix3000 I looked at your example and thought maybe function would replace void, but then I have another issue.
function OnTriggerEnter(other : Collider)
{
if (other.tag == "Player")
{
// value of 2 for Y axis to move up
coll.getComponent<Rigidbody>().addForce(Vector3, 0, 2, 0);
return;
}
}
This is a problem I have. It's one thing to have the trigger detect the player tag, it's another to have that trigger telling a cube to move up after the player comes into contact with the trigger. Don't understand how this could work because it seems to me there isn't any code that makes the trigger addForce to another object. And my goal with this is to make the trigger move a cube up and when the player exits the trigger, it moves down.
In this case you would just replace
coll.getComponent<Rigidbody>()
with
theGameobjectYouWant.getComponent<Rigidbody>()
Then you do a similar thing with OnTriggerExit to move it down again.
If you need more detailed explanations of OnTriggerEnter etc. just search the documentation :)
@Brullix3000
function OnTriggerEnter(other : Collider)
{
if (other.tag == "Player")
{
moveCube.getComponent<Rigidbody>().addForce(Vector3, 0, 2, 0);
return;
}
}
Unfortunately when I did this with positive and negative values with Enter and Exit functions I get errors.
Assets/trigger.js(5,50): BCE0043: Unexpected token: ). Assets/trigger.js(5,51): BCE0044: expecting ), found '.'. Assets/trigger.js(5,52): UCE0001: ';' expected. Insert a semicolon at the end.
Don't understand why it does this.