- Home /
AddForce from Two Sources
So in my game, the player controls through scripting. Particularly because I didn't know the character controller component existed at the time, and when I learned about it, the script was too firmly rooted in the game to remove.
Anyways, I have a player movement script operating exactly the way it's supposed to, with WASD controls. Here's what they look like.
if (Input.GetKey (KeyCode.A)) {
rigidbody2D.AddForce (Vector2.right * -movement);
}
if (Input.GetKey (KeyCode.W)) {
rigidbody2D.AddForce (Vector2.up * movement);
}
No problem. However if I punch in A and W at the same time, the player moves diagonally. That's fine, but the problem is that because force is being applied to the object from two sources, the object moves faster diagonally than it would if it were just the W or A key.
So anyone with a better grasp of coding than me know of a way to get the player to be pushed at speeds similar to normal movement speeds while both W & A are being pressed?
Answer by tanoshimi · Dec 27, 2014 at 09:06 AM
Try adding this after the end of your if conditions:
rigidbody2D.velocity = rigidbody2D.velocity.normalized * movement;
Player now moves at the same speed in every direction, albeit slower but adjusting the movement variable can fix that, however the player doesn't decelerate if the movement keys aren't being pressed.
How about this:
Vector2 dir = Vector2.zero;
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.A)) {
dir += (Vector2.right * -movement);
}
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.W)) {
dir += (Vector2.up * movement);
}
dir = Vector2.Clamp$$anonymous$$agnitude(dir, movement);
rigidbody2D.AddForce(dir);
It is basically the same as what tanoshimi describe, but is less likely to effect other things happening in the script!
That the script already has a variable called 'dir' threw me off for a bit, but once I got past that, this works perfectly! Thank you.
Your answer
Follow this Question
Related Questions
Dashing with rigidbody2D not working right 2 Answers
move 2d character affected by physics with velocity and/or add force 2 Answers
Best way to move a Rigidbody2D from point A to point B (Mouse Position) 3 Answers
Rigidbody2D x velocity not moving unless placed in FixedUpdate 1 Answer
Rigidbody2D AddForce only working with large numbers 2 Answers