Hey everyone. I am working on a tile base game and I need some help with the character movement. What I want is when the user clicks on a tile that is adjacent to the character, the character will move to that position. I was unsure about how to go about finding whether or not the tile that the user clicked on is adjacent to the character. I was wondering if any of you have already made a game like this and know a good way to accomplish this. I doesn’t seam to be that difficult, I just want a good and efficient method of doing this. Thanks for any help!
–CgRobot–
While someone may have a better suggestion…
I’d probably store the “map” as a 2D array of tiles. Then, all you’d have to do is:
- Convert the screen click to an index in your 2D array
- Compare the known index position of the player to the clicked index position
- If they’re within one element of each other (presumably in any direction), allow the move.
Obviously, you could apply other movement restrictions as necessary.
I was thinking about finding the distance between the character and the tile that was clicked, and if that distance is farther than the distance between the character and an adjacent tile, then the character can’t move; if the distance is, however, less than or equal to the distance between the character and an adjacent tile, then the character will move to that tile.
I have it working now. Here is the code that I used:
//Defined in the Update function (local variables)
var clickRay = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
var dist : float;
//Defined outside of Update function (global variables)
var distanceAllowed : float = 10;
var movesLeft : int = 2;
var canMove : boolean = true;
//The following code is placed inside the Update function
if(Input.GetAxis("Fire1"))
{
if(Physics.Raycast(clickRay, hit, 300))
{
//Calculates the distance between the tile clicked and Player 1
dist = Vector3.Distance(hit.transform.position, transform.position);
if(dist <= distanceAllowed)
{
if(movesLeft > 0)
{
transform.position.x = hit.transform.position.x;
transform.position.z = hit.transform.position.z;
movesLeft --;
if(movesLeft <= 0)
{
canMove = false;
}
}
else
{
//Display a message saying we can't move there
}
}
else
{
//Display a message saying we can't move there
}
}
}