- Home /
2D Pathfinding with Raycast
Greetings, I have a game with coffee concept. (2d) I have 5 tables in scene. I created a raycasting that when we click to the tables, my character goes to the tables to get orders. This is my code. My problem is, like on the picture below, i want it to use a path, instead of directly going to the point, because when it directly goes, it is ignoring the table, what i want is to not ignore table, and pass nearby of it. What way should i follow to achieve that?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float moveSpeed = 10f;
private Vector2 _lastClickedPos;
private bool _moving;
void Update()
{
RaycastHit2D rayHit = Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition));
if (Input.GetMouseButtonDown(0) && rayHit.collider != null)
{
_lastClickedPos = rayHit.transform.position;
_moving = true;
Debug.Log(_lastClickedPos);
}
// if we are moving and we are not on last clicked position
if (_moving && (Vector2) transform.position != _lastClickedPos)
{
float step = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, _lastClickedPos, step);
}
else
{
_moving = false;
}
}
}
Your answer
Follow this Question
Related Questions
Argument out of Range Exception Error - Parameter Name: Index 1 Answer
how can i use navigation in unity with spherical world ? 0 Answers
Checking vector3 gameObject is about to move to (pathfinding collision detection) 1 Answer
Dealing With Multiple Navmeshes 0 Answers
AI Movement Framework Recommendations for 2D Top Down Game 0 Answers