Box Collider 2Ds not colliding percisely
I finally managed to make my player move one pixel at a time with the script below. But now I have a new problem.
When the player collides with a wall, he goes into it just slightly. When he stops moving into the wall, he either stays a tiny bit into the wall, or is pushed a tiny bit away from the wall. Either way, when he begins moving again, he is not aligned with the grid you will see in the pictures.
Both the wall and the player have a BoxCollider2D, and the player has a RigidBody2D.
Script for moving
public float speed = 4f;
public float pixelsToUnit = 16f; // The pixels to units I'm using
public Rigidbody2D rigidBody;
private float scale;
void Start ()
{
rigidBody = GetComponent<Rigidbody2D> ();
scale = 1f / pixelsToUnit;
}
void FixedUpdate ()
{
UpdateDirection ();
}
public void UpdateDirection() {
if (Input.GetKey (KeyCode.UpArrow)) {
rigidBody.position = new Vector2(transform.position.x, transform.position.y + scale);
}
else if (Input.GetKey (KeyCode.DownArrow)) {
rigidBody.position = new Vector2(transform.position.x, transform.position.y - scale);
}
if (Input.GetKey (KeyCode.RightArrow)) {
rigidBody.position = new Vector2(transform.position.x + scale, transform.position.y);
}
if (Input.GetKey (KeyCode.LeftArrow)) {
rigidBody.position = new Vector2(transform.position.x - scale, transform.position.y);
}
}
Game begins, player lined up with grid
Wall problems (melded together for attachment limit)
You'll note in the two last pictures that the player is no longer lined up the grid and is no longer in sync with the pixels. He walks around just fine otherwise, this only happens after hitting a wall.
Your answer
Follow this Question
Related Questions
My first Game (Snake) and some Problems 1 Answer
Box Collider 2Ds not colliding perfectly 0 Answers
How can I make my character walk while pressing arrow keys? 2 Answers
how create animation drag like this 0 Answers
Realistic Soccer Ball Dribbling? 1 Answer