Hey Guys, looking for a little help with rotation here. I have a ball that I’m trying to roll along the ground. The left and right arrows turn the ball in the x-z plane, while the forward and backward arrows move it forward and backward. (This is all being done with physics and rigidbodies, rather than transforms.) My only problem is that I can’t use the default ‘forward’ vector of the transform since the ‘forward’ of a rolling ball is often pointed towards the ground or the sky, or any number of non-useful directions.
So what I’m trying to do is find the y angle rotation of the ball, then get a vector that is that rotation around the global ‘up,’ and use that as the new forward. It mostly works, except that somehow in my code there this weird course-correction thing happening. I’ll be rotating the ball and then hit forward and it will start for a second to roll in the correct forward direction for the ball, but then it will suddenly veer off to a slightly altered vector and I don’t know why. I was hoping someone could double-check my code and see if you can tell me what I’m doing wrong…
void FixedUpdate () {
//SPHERE MOVEMENT
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
//turning
if (Mathf.Abs(hor) > deadZone) {
rigidbody.AddTorque(Vector3.up * turnSpeed * Input.GetAxis("Horizontal"));
}
//get the y rotation value
float yRot = transform.rotation.eulerAngles.y;
//apply the y rotation to the global 'forward' vector3 to get the
//forward vector direction that our sphere is moving in
Vector3 newForward = Quaternion.AngleAxis(yRot, Vector3.up) * Vector3.forward.normalized;
//forward
if (Mathf.Abs(ver) > deadZone) {
//move forward in that direction
rigidbody.AddTorque(newForward * forwardSpeed * Input.GetAxis("Vertical") * -1);
}
}
Allow me to rephrase, since I suspect I might be doing this completely wrong.
What I want is to get a 2D rotation around the Y axis that corresponds to how much the side arrows have been pressed. When I press ‘forward’ I would like for the ball to roll in the direction of that rotation. Is this the correct way of doing so?
If you want the ball only to roll and spin either left or right (2D). Then you could do something as simple as the code below.
#pragma strict
var speed = 10;
function Start () {
}
function Update () {
if (Input.GetKey(KeyCode.RightArrow))
{
rigidbody.AddTorque(0,0,speed);
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
rigidbody.AddTorque(0,0,-speed);
}
}
This will spin the ball around the Z axis and also move the ball left and right to make it look like it’s rolling. Adjust speed to make it move and spin faster.
I think this is sort of what I’m already doing for left and right - but the problem is rolling forward. The ball starts to tilt to the side, so that its right-side directional vector is no longer parallel to the ground. Because of this, it begins to tilt and roll in odd directions. I need to get it to stop doing that.