Hey, so I’m doing some 2D grid based movement and my collision script is having a problem.
Here’s the script:
public class Movement : MonoBehaviour {
public float speed = 2.0f;
Vector3 pos;
Vector3 old;
Transform tr;
void Start()
{
pos = transform.position;
tr = transform;
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.UpArrow) && tr.position == pos)
{
pos += (Vector3.up);
}
else if (Input.GetKey(KeyCode.RightArrow) && tr.position == pos)
{
pos += (Vector3.right);
}
else if (Input.GetKey(KeyCode.DownArrow) && tr.position == pos)
{
pos += (Vector3.down);
}
else if (Input.GetKey(KeyCode.LeftArrow) && tr.position == pos)
{
pos += (Vector3.left);
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
void OnCollisionEnter2D()
{
Debug.Log ("Contact");
float x = transform.position.x;
float y = transform.position.y;
float z = transform.position.z;
if ((int)(x + 0.5) > (int)x && x > 0)
x = (int)x + 0.5f;
else if((int)(x - 0.5) < (int)x && x < 0)
x = (int)x - 0.5f;
else
x = (int)x;
if ((int)(y + 0.5) > (int)y && y > 0)
y = (int)y + 0.5f;
else if ((int)(y - 0.5) < (int)y && y < 0)
y = (int)y - 0.5f;
else
y = (int)y;
z = 0f;
Vector3 away = new Vector3(x, y, z);
pos = away;
}
}
It seems that the problem stems from world positions. If I put my world all in the negatives of world space than the left and down collisions will work. However, if I put my world in the positives of world space than only up and right collisions work.
Gif of problem:
Any thoughts on what is wrong in the code?