Hello, I’m writing a script for a 2d point/click game. The character moves to a place and adjusts itself to a grid. The problem is that, if it reaches by chance x0,y0 coordinates, it gets stuck and doesn’t move anywhere else: the destination is always set to x0, y0. Also, if i don’t set the starting position in the start method, the player moves automatically towards x0,y0. I don’t know what it’s happening…
Here is the code:
public class Movement : MonoBehaviour
{
public Animator anim;
public int moveSpeed = 4;
public Vector3 destination;
void Start()
{
anim = GetComponent<Animator>();
anim.SetBool("is_right", true); // the bools are used to get the animations working
anim.SetBool("is_left", false);
destination = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
destination = new Vector3(Mathf.RoundToInt((mousePosition.x*2)/2),
Mathf.RoundToInt((mousePosition.y*2)/2),
transform.position.z);
}
MovePlayer();
StopMovement();
}
void MovePlayer()
{
//this movement animates the character going right, the if statements decide weather the player is moving up, right, down (moveright anim) or left (left anim)
if ((destination.x > transform.position.x) || ((destination.x == transform.position.x) & (destination.y != transform.position.y)))
{
anim.SetBool("is_left", false);
anim.SetBool("is_right", false);
anim.SetBool("go_right", true);
transform.position = Vector3.MoveTowards(transform.position, destination, moveSpeed * Time.deltaTime);
}
//this movement animates the character going left
else if (destination.x < transform.position.x)
{
anim.SetBool("is_left", false);
anim.SetBool("is_right", false);
anim.SetBool("go_left", true);
transform.position = Vector3.MoveTowards(transform.position, destination, moveSpeed * Time.deltaTime);
}
}
void StopMovement()
{
//arrivo
if (Vector3.Distance(transform.position, destination) == 0 && anim.GetCurrentAnimatorStateInfo(0).IsTag("right"))
{
anim.SetBool("is_right", true);
anim.SetBool("go_right", false);
}
else if (Vector3.Distance(transform.position, destination) == 0 && anim.GetCurrentAnimatorStateInfo(0).IsTag("left"))
{
anim.SetBool("is_left", true);
anim.SetBool("go_left", false);
}
}
}