- Home /
Rolling Ball Code Isn't Working
I am new at Unity and I have been trying to make a code for a game similar to super monkey ball or marble blast gold. The problem is that the code I am using isn't working. Can someone please help. Here is my code.
function Update () {
if (Input.GetKey ("up"))
rigidbody.AddForce (Vector3.foward * 10);
if (Input.GetKey ("down"))
rigidbody.AddForce (Vector3.backward * 10);
if (Input.GetKey ("left"))
rigidbody.AddForce (Vector3.left * 10);
if (Input.GetKey ("right"));
rigidbody.AddForce (Vector3.right * 10);
}
Answer by datorum · Aug 14, 2011 at 01:44 PM
There are several possibilities here. One could be that the applied force is too small another one could be that you apply the force to the wrong rigidBody or you don't even receive the keyboard input. Try the following:
function Update () {
if (Input.GetKey ("up"))
{
rigidbody.AddForce (Vector3.foward * 10);
Debug.Log("up pressed");
}
...
}
if you don't get a message in the console, you know that the keyboard never "arrives" correctly. If you get a message just increase 10 to 1000 or something way bigger. Trial and Error: just eliminate different possible error sources one after another.
Answer by Waz · Aug 14, 2011 at 01:50 PM
To roll a ball, I recommend AddTorque (I.e. spin it) and let friction do the work. Otherwise you get unnatural effects, like in-air acceleration. For playability, a combination may be needed.
It says NullReferenceException Object Reference not set to an instance of an object.
Don't you think you should edit your Question with that vital information? Way more intelligent and informative than "isn't working".
Answer by djfluffwug · Oct 07, 2011 at 04:05 PM
The problem is you forgot to put in the {}'s.
Wrong Way:
if (Input.GetKey ("down")) rigidbody.AddForce (Vector3.backward * 10);
...
Right Way:
if (Input.GetKey ("down")) { rigidbody.AddForce (Vector3.backward * 10); }
No, that format works. It's not the prettiest, or the safest, but it is legal code.
Oh does it? Wow, I guess I learnt something new. I tried that a few months ago and it didn't work. ($$anonymous$$ust have stuffed up somewhere else). Thanks for the heads up.
Answer by djfluffwug · Oct 08, 2011 at 05:56 AM
Oh, I see one of the problems.
You have spelt Forward incorrectly. It is Forward, not foward.
Also, there is no Backward in unity. You have to instead use forward but the negative of it.
For example:
if (Input.GetKey ("down"))
rigidbody.AddForce (Vector3.forward * -10;
//This will give the ball a force of -10 in the forward direction meaning the ball will roll backwards.
Answer by thegdeveloper · Feb 28, 2013 at 03:00 AM
Never use the addForce and addTorque, basically anything that has to do with the physics on update. You must applythem on FixedUpdate
Your answer
