- Home /
Using Add Force for character control
Hi there I've been working on a game for a while now and recently realised how adding a force to my player character could be better than changing its transform.position for collisions however I am struggling to convert my old script to use AddForce.
Here is my script (you can see a commented line of how I tried to get the same effect but failed)
//On Screen Controls
direction = new Vector3(joyScript.position.x, 0, joyScript.position.y);
if (direction.magnitude > 0.1f)
{
Vector3 rightMovement = right * ps3speed * Time.deltaTime * joyScript.position.x;
Vector3 upMovement = forward * ps3speed * Time.deltaTime * joyScript.position.y;
Vector3 heading = Vector3.Normalize(rightMovement + upMovement);
transform.forward = heading;
transform.position += rightMovement;
transform.position += upMovement;
//playerModel.rigidbody.AddForce(transform.forward * direction.magnitude);
playerModel.animation.Play("runforward");
}
else
{
playerModel.animation.CrossFade("idle");
}
If anyone could provide some assistance it would be much appreciated :) Thanks
Are you using RigidBody for your character controller? If not, it won't work.
I've changed the code to effect the correct rigidbody
//On Screen Controls
direction = new Vector3(joyScript.position.x, 0, joyScript.position.y);
if (direction.magnitude > 0.1f)
{
Vector3 right$$anonymous$$ovement = right * ps3speed * Time.deltaTime * joyScript.position.x;
Vector3 up$$anonymous$$ovement = forward * ps3speed * Time.deltaTime * joyScript.position.y;
Vector3 heading = Vector3.Normalize(right$$anonymous$$ovement + up$$anonymous$$ovement);
transform.forward = heading;
transform.position += right$$anonymous$$ovement;
transform.position += up$$anonymous$$ovement;
//rigidbody.AddForce(right$$anonymous$$ovement * direction.magnitude);
//rigidbody.AddForce(up$$anonymous$$ovement * direction.magnitude);
//rigidbody.AddForce(transform.forward * direction.magnitude);
player$$anonymous$$odel.animation.Play("runforward");
player$$anonymous$$odel.animation["runforward"].speed = direction.magnitude;
}
else
{
player$$anonymous$$odel.animation.CrossFade("idle");
}
Still doesn't work however :(
You might wanna check this one out: http://wiki.unity3d.com/index.php?title=RigidbodyFPSWalker
Thanks Tasha I was indeed trying to apply force to the incorrect rigidbody at first :)
Answer by vividhelix · Nov 05, 2013 at 06:01 AM
I would expose the magnitude, or add another factor in that multiplication there and fiddle with it in the editor. Small enough values for AddForce will not make any difference.
So make this:
public float forceFactor;
and
playerModel.rigidbody.AddForce(forceFactor * transform.forward * direction.magnitude);
Cool I'm not at work yet but when I do I'll give it a try, thanks :)
Thanks vivid it was that the value was too low, I was trying to change it via code, then realised I was setting it really low via the editor as it was a public variable. Thanks!