- Home /
2D Top Down Movement
I've just stared to make a 2D top down game. But I cant get past the movement.
The first thing I tried was transform.translate, but the collisions are bouncy and the over all movement is choppy.
The second thing I tried was addforce, which is a lot smoother and collisions are fine, but the movement is all drifty, when you let go of the key, you keep moving. You start off slow and keep accelerating. No matter how much I change the speed, and the friction, it isn't how i want it.
Is there any 2D top down moving script that makes my player move at a constant speed until I let go of the button in which the player will stop immediately?
Answer by Zoogyburger · Aug 25, 2016 at 02:34 AM
Here's a very simple 2d movement script:
using UnityEngine;
using System.Collections;
// PlayerScript requires the GameObject to have a Rigidbody2D component
[RequireComponent (typeof (Rigidbody2D))]
public class PlayerScript : MonoBehaviour {
public float playerSpeed = 4f;
void Start () {
}
void FixedUpdate () {
Vector2 targetVelocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
GetComponent<Rigidbody2D>().velocity=targetVelocity * playerSpeed;
}
}
Answer by Pleroma · Aug 25, 2016 at 06:09 AM
I'm presently developing a 2D top down game as well, and I ran into a similar problem. Setting your Velocity has been much more fruitful for me than adding force, as @Zoogyburger suggested. However, if that's still too floaty for you, you might want to do what I did, and use GetAxisRaw instead of GetAxis.
GetAxis returns a float between -1 and 1, which depending on the speed of the transition from 0 to 1 and back again, might leave your character moving a little even after you've released the key. I understand unity has some very interesting tools to tune how quickly the GetAxis float changes, but for my game (and possibly yours as well), it was overkill. GetAxisRaw returns either -1, 0, or 1. So when you release the key, the GetAxis value immediately drops to 0 -- the character stops.
If GetAxisRaw is too snappy for your game, I would suggest looking at the Input Manager in the Unity API. That should have all the tools you need.
Your answer
![](https://koobas.hobune.stream/wayback/20220612091418im_/https://answers.unity.com/themes/thub/images/avi.jpg)