Alex
Alex

Reputation: 13

Unity 2D Character Movement

For the game I'm trying to build, I want my player objects to move when 'W/A/S/D' are held down.

For example, if I wanted to move right, I'd have to hold down 'D'.

I've tried using Rigidbody2D.AddForce, but I dislike the feel of the movement it creates.

I'm looking for instant movement and stopping, as opposed to any acceleration/decceleration.

Any ideas?

Thank you!!! Alex

Upvotes: 1

Views: 931

Answers (1)

greenPadawan
greenPadawan

Reputation: 1571

You can try something like this. In the update method, fetch the movement values from WASD keys using the following code.

MovementInputValue = Input.GetAxis ("VerticalAxis_name");
TurnInputValue = Input.GetAxis ("HorizontalAxis_name");

Then, in the FixedUpdate method, move the object with the following code.

// For moving

    Vector3 movement = transform.forward * MovementInputValue * m_Speed * Time.deltaTime;
    rigidbody.MovePosition(rigidbody.position + movement);

 //For turning
    float turn = TurnInputValue * m_TurnSpeed * Time.deltaTime;
    Quaternion turnRotation = Quaternion.Euler (0f, turn, 0f);
    rigidbody.MoveRotation (rigidbody.rotation * turnRotation);

This code is written for 3D movement, but you can easily change it to 2D

Upvotes: 0

Related Questions