- Home /
Accesing variable previously declared?
Hi everyone, I'm having a difficult time trying to make a very simple animation.
I have a sphere (testObject1) which I want to move left and right, and switch this movement when it collides to with a rigidbody.
So, I came up with this:
var speed = 0.10;
var dropPoint = 1;
function Update () {
if(dropPoint == 1){
transform.Translate(0, 0, speed);
}else{
transform.Translate(0, 0, speed - (speed * 2));
}
}
function OnCollisionEnter(collision : Collision) {
for (var contact : ContactPoint in collision.contacts) {
if(collision.collider == "testObject3"){
dropPoint = 2;
}else{
if(collision.collider == "testObject2"){
dropPoint = 1;
}
}
if(collision.collider != "testFloor"){
print(collision.collider);
}
}
}
So, when I hit play, the sphere starts moving in Z direction, collides with the testObject3 and it keeps going in the same direction...
What am I doing wrong here?
Thanks!
Answer by Bunny83 · Oct 03, 2011 at 02:06 PM
Your problem is that you can't compare a Collider with a string!
I guess "testObject3" and "testObject2" are the names of those GameObjects, right? So you have to check the name of the GameObject:
if(collision.collider.name == "testObject3"){
dropPoint = 2;
}
else if(collision.collider.name == "testObject2"){
dropPoint = 1;
}
Another funny thing is your "`speed - (speed * 2)`" :D
It's the same as "`-speed`"
Thaaaaaaaaaanks very much! I guess I just imagine the worst way to do something and just do it that way :P Thanks!
Answer by timsk · Oct 03, 2011 at 12:37 PM
try this:
if(dropPoint == 1){
transform.Translate(0, 0, speed);
}else if(dropPoint ==2){
transform.Translate(0, 0, speed - (speed * 2));
}
}
Debug the colliders too, make sure they are colliding correctly.
Also, instead of using
if(dropPoint ==2)
you might want to use
if(dropPoint >1)
Just for versatility.
Your answer
