Hello There! I’m developing a 2d top down game.
The movement is done by clicking on the target location (which adjusts itself to a tilegrid), and it works just fine.
The problem is that if the character encounters a collider on its way (hence stopping the movement), the readjusting to the grid is extremely laggy when the collision point is in an “uncomfortable position”; so, i thought of adding a raycast, in order to preemptively readjust the route to the new target position (the collision point). The problem is; the character stopped moving. Been searching all over the internet, but didn’t find anything.
public float MoveSpeed = 3;
private Vector3 target;
// these are the variables that should help the raycast work
Vector3 raycastDir;
float raycastDist;
RaycastHit2D hit;
void Start()
{
target = transform.position;
//distance, direction and hitpoint of the raycast
raycastDist = Vector3.Distance(transform.position, target);
raycastDir = (target - transform.position).normalized;
hit = Physics2D.Raycast(transform.position, raycastDir);
}
void Update()
{
//movement on mousclick and rounding to adjust to the grid
if (Input.GetMouseButtonDown(0))
{
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.x = Mathf.RoundToInt(target.x);
target.y = Mathf.RoundToInt(target.y);
target.z = transform.position.z;
//the raycast part
if (Physics2D.Raycast(transform.position, raycastDir, raycastDist))
{
target = hit.point;
target.x = Mathf.RoundToInt(target.x*2)/2;
target.y = Mathf.RoundToInt(target.y*2)/2;
target.z = transform.position.z;
}
}
changeposition()
}
void changeposition ()
{
transform.position = Vector2.MoveTowards(transform.position, target, MoveSpeed * Time.deltaTime);
}
Thanks for your help!