2d Grid Based Movement, Won't Work
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
C# delaying command 0 Answers
I need help with AI,Force not working 0 Answers
How to align 2d object to terrain? 2 Answers
I was trying to make my game in unity but I got stuck while making "game over" part. please help! 0 Answers
2D AI movement 0 Answers