Hello.
I’m a novice developer.
There is a rectangular grid tile map.
When I act in the direction the player is looking at,
I want to change the data on the 1*1 position tile in the direction I am looking at.
I knew how to store data on each tile.
Is there a way to find only one particular tile in the direction you’re looking at?
I think I can use a raycast, but I don’t have a clue.
I want the targeting function of a normal 2D farm simulation.
The style may be awkward because it’s a translator. Please excuse me.
You could have an array of grids Transform[] gridTileArray
and check which tile is closest to the player:
Transform closestTile = null;
float closestTileDistance = -1;
for (int i=0; i < gridTileArray.length; i++){
float currentDistance = Vector2.Distance(gridTileArray[i], player.position);
if (currentDistance < closestTileDistance){
closestTileDistance = currentDistance;
closestTile = gridTileArray[i];
}
}
if (closestTile == null){
Debug.LogWarning("An error occured, either the gridTileArray is empty, or the code has an error");
}
Ok, so what ai would do, now that I understood better is:
Collider2D frontTile;
frontTile = Physics2D.CastSphere(player.position + player.forward * distance, radius);
Wrote from phone so there may be sintax errors
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Player : MonoBehaviour
{
float speed = 0.01f;
[SerializeField]
Transform closestTile = null;
[SerializeField]
float closestTileDistance = 100;
public static List reachTiles = new List();
private void Update()
{
if (Input.GetKey(KeyCode.UpArrow))
{
transform.position += new Vector3(0, speed,0);
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.position += new Vector3(0, -speed, 0);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position += new Vector3(-speed, 0, 0);
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += new Vector3(speed, 0, 0);
}
for (int i = 0; i < reachTiles.Count; i++)
{
float currentDistance = Vector2.Distance(reachTiles[i].position, gameObject.transform.position);
if (currentDistance < closestTileDistance)
{
closestTileDistance = currentDistance;
closestTile = reachTiles[i];
}
}
if (closestTile == null)
{
Debug.LogWarning("An error occured, either the gridTileArray is empty, or the code has an error");
}
else
{
Debug.Log(closestTile);
closestTileDistance = 100;
closestTile = null;
}
}
}