Hi,
I’m quite new to Unity, and I’m trying to bring the player to a clicked point.
What I’ve tried to do is in an update function, always move the player towards the last clicked point, and if he has reached it, not move him anymore.
However this code makes Unity crash. Any idea ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Animator animator;
Vector2 mousePos2D;
bool hasReachedPoint = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);
}
if(mousePos2D.x == transform.position.x && mousePos2D.y == transform.position.y)
{
hasReachedPoint = true;
}
if (!hasReachedPoint)
{
while(mousePos2D.x != transform.position.x)
{
float movespeed = 0.0f;
movespeed++;
transform.position = new Vector2(transform.position.x + movespeed * Time.deltaTime, transform.position.y);
}
while (mousePos2D.y != transform.position.y)
{
float movespeed = 0.0f;
movespeed++;
transform.position = new Vector2(transform.position.x, transform.position.y + movespeed * Time.deltaTime);
}
}
}
}