I started making a D&D-style turn based tactic game. I have a problem with my tilemap.
I made a script to find the location on the tilemap for my character and for the tile I clicked with the mouse. (Both are working: it shows me locations like (3,-2) etc.)
But when I try to move my character from location to target... My character is stuck, always in one place ~(0,0) in the gap between cells. Here is the code.
using UnityEngine;
using UnityEngine.Tilemaps;
public class CharacterMovement : MonoBehaviour
{
public Tilemap tilemap;
public float moveSpeed = 50f;
public bool hasMoved = false;
private Vector2Int targetPosition;
private Vector2Int characterLocation;
private void Update()
{
MoveToClickedTile();
}
private void MoveToClickedTile()
{
// Check for left mouse button click
if (Input.GetMouseButtonDown(0) && !hasMoved)
{
GetMouseLeftClickPosition();
GetCharacterTileLocation();
// works
print(targetPosition + "target");
print(characterLocation + "character");
// doesnt work
transform.position = Vector2.MoveTowards(characterLocation, targetPosition, moveSpeed * Time.deltaTime);
hasMoved = true;
}
}
private void GetMouseLeftClickPosition()
{
Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition = (Vector2Int)tilemap.WorldToCell(mouseWorldPos);
}
private void GetCharacterTileLocation()
{
characterLocation = (Vector2Int)tilemap.WorldToCell(transform.position);
}
}
Is the problem that my character does not "belong" to the tilemap? I made it as a separate game object, and its transform location is really strange, I don't understand why.
But when I made the character separate from the tilemap, it had a weird box that was much more bigger than the character, and I could not click on it to find out what it was.
Vector2.OneStepTowards
might be a clearer name for it) Are you able to solve your problem using the advice at the earlier Q&A link? – DMGregory Sep 08 '23 at 17:01