- Home /
Why does my sphere object stop moving on collision?
Hi,
what a refreshingly busy site! I'm a new unity user working my way through one tutorial after the other.
In my experimental unity scene i have a sphere that's supposed to be bouncing between two caps infinitely (see picture). The sphere's speed is adjustable in the editor (default: 1) by a public speed-variable in the controlling script. As I increase speed to a value of round 3 or 4 the sphere still bounces in between the caps a couple of times (how many time differs everytime) and then stops on collision with one of the caps, velocity being 0 at this point.
code:
public var speed : float;
function Start(){
speed = 1;
rigidbody.velocity.y = speed;
}
function Update () {
Debug.Log(rigidbody.velocity.y);
}
function OnCollisionEnter(collision : Collision) {
Debug.Log(rigidbody.velocity.y);
if(rigidbody.velocity.y > 0){
rigidbody.velocity.y = -speed;
}else{
rigidbody.velocity.y = speed;
}
}
What is it that I'm not considering?
scene:
Answer by Scribe · Aug 19, 2014 at 01:12 PM
Does the same happen if you change the caps to triggers (check the Is Trigger box of their colliders) and change your code to use OnTriggerEnter(other : Collider)?
I believe the issue is probably that OnCollisionEnter means the ball has collided, and if it has collided then it's speed will be being changed, it will therefore be quite likely that at the time of collision the speed is set to 0 and therefore rigidbody.velocity.y = speed; will be called, even if that is not actually the correct direction!
thanks Scribe. it actually works with OnTriggerEnter(other : Collider) i.e. the sphere no longer stops. Your explanation sounds plausible but I don't see why it always worked correctly for a couple of bounces and then failed at the 3rd to 10th time. i guess it must have something to do with the internal workings of unity.
glad you got it working. I'm not sure why it takes 3 before it happens but it would make sense why it happens after a random number, out of interest, do you remember what your Debug.Log was printing with your old setup?
Also please! It helps others find the answer and I get karma! woop :D