- Home /
Inhibit force from doubling when 2 axes are active
I'm using a rolling ball controller from the Circular Force Package found on the asset store. My problem is when I move the ball in a diagonal direction, the force becomes doubled when both axes are active. I can't figure out how to inhibit the force while both are active. I tried dividing the force by 2 when both are active, but that didn't give the best result. Any suggestions are greatly appreciated.
Here's part of the code...
void FixedUpdate()
{
//Right Left controls
float horMovement = movementForce * Input.GetAxis("Horizontal");
//Forward Backward controls
float verMovement = movementForce * Input.GetAxis("Vertical");
//Up Down controls. Note: For Zero G
float floatMovement = movementForce * Input.GetAxis("Mouse ScrollWheel");
if (horMovement != 0)
{
this.transform.rigidbody.AddForce(new Vector3(horMovement, 0, 0), ForceMode.Impulse);
}
else
if (verMovement != 0)
{
this.transform.rigidbody.AddForce(new Vector3(0, 0, verMovement), ForceMode.Impulse);
}
if (floatMovement != 0)
{
this.transform.rigidbody.AddForce(new Vector3(0, floatMovement * 4, 0), ForceMode.Impulse);
}
}
//Enables/Disable the circular gravity
private void EnableCircularGravity(bool enable)
{
CircularGravity circularGravity = this.GetComponent<CircularGravity>();
circularGravity.enable = enable;
}
}
Comment
Answer by Bunny83 · Jun 27, 2013 at 07:58 AM
Just use Vector3.ClampMagnitude like this:
void FixedUpdate()
{
Vector3 moveDirection = new Vector3(
Input.GetAxis("Horizontal"),
0,
Input.GetAxis("Vertical")
);
moveDirection = Vector3.ClampMagnitude(moveDirection,1.0f);
moveDirection.y = Input.GetAxis("Mouse ScrollWheel")*4;
rigidbody.AddForce(moveDirection * movementForce, ForceMode.Impulse);
}
I'm not sure why you use ForceMode.Impulse since it's ment for one-time boosts relative to the objects mass. You shouldn't do this every frame. I would probably do something like:
void FixedUpdate()
{
Vector3 moveDirection = new Vector3(
Input.GetAxis("Horizontal"),
0,
Input.GetAxis("Vertical")
);
moveDirection = Vector3.ClampMagnitude(moveDirection,1.0f);
Vector3 upMovement = Vector3.up * Input.GetAxis("Mouse ScrollWheel")*4;
rigidbody.AddForce(moveDirection * movementForce, ForceMode.Acceleration);
if (upMovement != 0.0f)
rigidbody.AddForce(upMovement * movementForce, ForceMode.Impulse);
}