- Home /
Mysterious behaviour of moving sphere
I'm trying to write a first simple game, as a learning exercise. So far, it's just a small ball rolling randomly on a large plane. It is more or less working. But I have a couple of questions about its behaviour which seems completely incomprehensible to me. Also one question about the syntax. What I wanted to do was randomly rotate the sphere around the y axis at intervals and then move the ball forward, so it's changing direction randomly. Here is the movement code:
float directionChange = new float ();
directionChange = (Random.Range (-rotationRange, rotationRange));
transform.Rotate (0.0f, directionChange, 0.0f);
rigidbody.AddForce (transform.forward * speed * Time.deltaTime);
The sphere is 0.5 radius, positioned at 0.25 on the y axis. It is non kinematic and acting under gravity, yet looking at the sphere in the inspector when its running, the y coordinate is dithering randomly between about 0.2299 and 0.40. I can't see anything in the code that would be affecting this value at all. When I check contrain y position, the sphere stops moving altogether.
The sphere is not just randomly changing direction, but also randomly changing speed, which I don't want. As far as I can see, I am only applying an unchanged force in the forward direction, so how can it be changing speed?
The syntax question, I understood the first two lines of code above to be equivalent to:
float directionChange = new float (Random.Range (-rotationRange, rotationRange));
but when I write this, I get the compiler error,
The type `float' does not contain a constructor that takes `1' arguments
I'm obviously misunderstanding something. Any help on any of these questions would be welcome. Thanks.
$$anonymous$$aybe you know this, but unity actually did a tutorial on a rolling-ball type game. If you're interested here it is:
Yes, thanks, I just finished that tutorial and wanted to build on it.
Answer by whydoidoit · Mar 09, 2014 at 01:45 PM
Ok so the ball is rolling which means that sometimes it's transform is facing downwards and sometimes upwards. As you add the force it is being pushed into the ground or push up away from it.
You are also adding force, this is increasing the speed of your sphere, apparently at random due to the amount it pushes into the ground.
You should calculate your random force like this:
float directionChange = Random.Range(-rotationRange, rotationRange);
Then perhaps
var forceDirection = Quaternion.AngleAxis(transform.eulerAngles.y + directionChange, Vector.up) * Vector3.forward;
This takes the current y rotation and adds on the direction change. If you don't have any friction then the ball will continue to accelerate as you continue to add force.
I see, that makes a lot of sense. I'll try that. Thanks very much for your help!