How do i make a player move to only the certain spots?


The blue circles should be only able to move to the squared next to them (diagonally aswell)

This is my code so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClickToMove : MonoBehaviour
{
public static List moveableObjects = new List();
public float speed = 5f;

private Vector3 target;
private bool selected;
// Start is called before the first frame update
void Start()
{
    moveableObjects.Add(this);
    target = transform.position;        
}

// Update is called once per frame
void Update()
{
    if(Input.GetMouseButtonDown(0) && selected)
    {
        target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        target.z = transform.position.z;
    }
    transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
private void OnMouseDown()
{
    selected = true;
    gameObject.GetComponent<SpriteRenderer>().color = Color.green;

    foreach(ClickToMove obj in moveableObjects)
    {
        if(obj != this)
        {
            obj.selected = false;
            obj.gameObject.GetComponent<SpriteRenderer>().color = Color.white;
        }
    }
}

}

Judging from the above I am not sure if you are in an actual grid or not.

If you are, make a grid in code (some type of 2D collection) and track all the positions and permissions yourself, then use that to know where to put or move stuff.

More generally, if you’re doing a board game of some kind:

  • highlight the available places you can go so the user knows
  • if they click on those available place, move the piece
  • if they click somewhere else, don’t move it, perhaps show a message
  • when the piece arrives, update the internal game logic however necessary

Tracking what is legal is entirely dependent on the logic of whatever game you’re making. If you are not sure what that means, start with some small simple board game tutorials such as making tic-tac-toe in Unity.