2D Grid Based Movement, Not Working
Good day, below is my the code, I can't seem to figure out why my MoveTowards is not working. I've tried wrapping it in a while loop when the condition of current position does not match movetowards position. This caused Unity to freeze. I then tried to run MoveToPosition() as a coroutine, this resulted in a pause between movement (Not Fluid) and then would pick up speed exponentially between subsequent moves.
Code may have slight grammatical errors, due to not being at home and rewriting in notepad lol
private Vector3 position;
private float speed = 2.0f;
void Start ()
{
position = transform.position;
}
void FixedUpdate()
{
// Checks if keys have been pressed
CheckForInput();
}
// Checks if there is input for movement
void CheckForInput()
{
// UP
if (Input.GetKey(KeyCode.W) && transform.position == position)
{
if (CheckForCollision(Vector3.up) == false)
{
position += Vector3.up;
MoveToPosition();
}
}
// DOWN
else if (Input.GetKey(KeyCode.S) && transform.position == position)
{
if (CheckForCollision(Vector3.down) == false)
{
position += Vector3.down;
MoveToPosition();
}
}
// LEFT
else if (Input.GetKey(KeyCode.A) && transform.position == position)
{
if (CheckForCollision(Vector3.left) == false)
{
position += Vector3.left;
MoveToPosition();
}
}
// RIGHT
else if (Input.GetKey(KeyCode.D) && transform.position == position)
{
if (CheckForCollision(Vector3.right) == false)
{
position += Vector3.right;
MoveToPosition();
}
}
}
// Checks if there will be a collision in input direction
bool CheckForCollision(Vector3 direction)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, 1f);
if (hit.collider == null)
return false;
else
return true;
}
// Moves to a position when potential collison is false
void MoveToPosition()
{
transform.position = Vector3.MoveTowards(transform.position, position, Time.deltaTime * speed);
}
Your answer

Follow this Question
Related Questions
Editor/Game random crash at Scene launch 3 Answers
C# delaying command 0 Answers
Object with rigidbody2D doesn't move when it's supposed to, 0 Answers
I need help with AI,Force not working 0 Answers
How do I make a ball bounce in a circle? 0 Answers