Hello everyone
I’m new to Unity 2D system and I have some doubts about making a 2D movement with physics.
Here’s my current code to WASD movement
int Speed = 30;
float maxSpeed = 8f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
bool movingX = (Input.GetAxis ("Horizontal") != 0);
bool movingY = (Input.GetAxis("Vertical") != 0);
float _xAccel = 0, _yAccel = 0;
_xAccel = Input.GetAxis ("Horizontal");
_yAccel = Input.GetAxis ("Vertical");
Vector2 vec = new Vector2 (_xAccel, _yAccel);
rigidbody2D.AddForce (vec * this.Speed);
rigidbody2D.velocity = Vector2.ClampMagnitude(rigidbody2D.velocity, maxSpeed);
float newX = rigidbody2D.velocity.x, newY = rigidbody2D.velocity.y;
if (!movingX)
newX *= 0.9f;
if (!movingY)
newY *= 0.9f;
rigidbody2D.velocity = new Vector2 (newX, newY);
}
The code works but the player doesn’t have a smooth movement, It seems like its oscillating.
Is it okay to call AddForce every frame?
Thanks from now
Regards