Question by
PetomPixel · Oct 03, 2016 at 08:15 PM ·
movementpixelboxcollider2d
Box Collider 2Ds not colliding perfectly
I managed to make a character who moves one pixel at a time precisely, so that he's always lined up with this grid, no matter how I move him
Script for movement
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);
}
}
The problem I'm having is, one he collides with another 2D Box Collider, like a wall, he gets offset. Specifically, he walks a fraction of a pixel into the wall, then get pushed a fraction of a pixel away from the wall, upsetting his pixel perfection, as shown:
Top half, inside the wall. Bottom half, pushed away from the wall
How do I fix this?
ingame-1.png
(12.4 kB)
ingame-4.png
(5.6 kB)
Comment