I added a collision mechanic, but It does not work as intended.
Whenever I go in from the y axis, I do not get close enough, and when I go in from the x axis, I just phase right through
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private bool isMoving;
private float moveX;
private float moveY;
private Vector2 input;
private Animator an;
public LayerMask solidObjects;
private void Awake()
{
an = GetComponent<Animator>();
}
private void Update()
{
if (!isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
if (input != Vector2.zero)
{
an.SetFloat("moveX", input.x);
an.SetFloat("moveY", input.y);
var targetPos = transform.position;
targetPos.x += input.x;
targetPos.y += input.y;
if (isWalkable(targetPos))
StartCoroutine(Move(targetPos));
}
}
an.SetBool("isMoving", isMoving);
}
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
private bool isWalkable(Vector3 targetPos)
{
if(Physics2D.OverlapCircle(targetPos, 0.2f, solidObjects) != null)
{
return false;
}
return true;
}
}