- Home /
Physics on a Ball
Hi, I have a ball that I want to properly display physics. What I mean by this is that I want to ball to roll properly from left to right, and then, if I change direction, I want the momentum to slow the ball down and accelerate from right to left. Additionally, when I jump, I don't want the ball to fall from left to right and right to left solely based on the user rocking the phone back and forth. Right now, I am having trouble with both the physics of movement and the physics of the ball in the air
My code for movement:
function Update () { var dir : Vector3 = Vector3.zero; dir.x = -Input.acceleration.y.5; transform.position.x += dir.x; //dir.y = -Input.acceleration.x.5; //transform.position.y += dir.y; }My code for jumping:
var dir : Vector3 = Vector3.zero; var isFalling : boolean=true;
function Update () { var fingerCount = 0; for (var touch : Touch in Input.touches) { if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled) fingerCount++; } if (fingerCount > 0) //&& !isFalling){ rigidbody.velocity.y=7; } isFalling=true; function OnCollisionStay(collisionInfo : Collision) { isFalling=false; }
What specific problem are you trying to fix? If you're just asking a general question, you should probably check the Unity physics manual or look for other tutorials, first.
I guess I was asking too many questions at once, so I'll just focus on getting the ball movement to operate correctly. I've changed the constraints of the rigidbody, but when I run this on my phone, there is no rolling. Additionally, when I change direction, there is no slow down and readjustment to the change in direction. So, I'd like assistance with what I must have done wrong on that issue.
Answer by aldonaletto · Apr 13, 2012 at 01:28 AM
You can't use physics and move by modifying transform.position!. You should use rigidbody.AddForce to move the ball - something like this:
var force: float = 5.0;
function Update () { var dir : Vector3 = Vector3.zero; dir.x = -Input.acceleration.y; dir.z = Input.acceleration.x; rigidbody.AddForce(dir * force); } To jump, set the rigidbody.velocity.y to the jump speed, as you seem to be already doing.