- Home /
Player movement on a grid?
I am building a strategy game with grid-based movement. I have sprites on each tile surrounding the player to show their range of movement.
I am trying to implement a script that moves the player to whichever highlight they click on but I cannot even get it to recognize the player's position. Any help?
public class PlayerMovement : MonoBehaviour
{
public GameObject player;
public Vector3 targetPos;
private float speed = 20f;
public Vector3 playerPos;
void Start ()
{
playerPos = player.transform.position;
}
void OnMouseExit ()
{
targetPos = playerPos;
}
void OnMouseDown ()
{
targetPos = transform.position;
}
void Update ()
{
float step = speed * Time.deltaTime;
player.transform.position = Vector3.MoveTowards(playerPos, targetPos, step);
}
}
Answer by FlaSh-G · Feb 11 at 02:01 PM
Vector3
is a struct, so it has no reference semantics. In Start()
, you copy the player's position into a variable called playerPos
, but there is no connection between that variable and the player transform. Updating the player's position will not change the value of that variable, it keeps its initial value after Start()
. Hence, your Update()
will set the player position to a position near the starting position, never really moving away from it.
In line 22
, replace playerPos
with player.transform.position
.
In addition... is this script on each tile? Because you're setting transform.position
as the target position for the player. If you have this script on each tile, first off, that's a lot of script instances. And secondly, each of these script instances is constantly manipulating the player position to a target position. All tiles but one will have an incorrect target position set, so they're constantly pulling the player into a wrong direction.
Instead, have one target position variable. Probably in a player script. Then have another script check the mouse position and set a new target position for the player on click.
Your answer
Follow this Question
Related Questions
How do I swap two gameObjects order in a list? 2 Answers
Can't get the animation to trigger while the player is moving 0 Answers
How to find sprite at grid location? 1 Answer
How can I Stop grid based movement on One or more access? 0 Answers
Road placement and road removement during run mode 0 Answers