Question by
KingMatthew101 · Sep 22, 2021 at 08:29 PM ·
coroutinemovement scriptefficiencyclick to move
Improving Click-to-Move Movement Script (2D)
Hello there! I'm currently working on a 2d game where one controls player units on a screen by clicking to select them, then choosing another point on the screen for them to move too. So far, I've created a script that does this, but only about 20% of the time. Are there any suggestions or tips on how to improve the below system to be more reliable and run smoother? Or any blaring mistakes that are causing the unreliability? Thank you for the help!
using UnityEngine;
using System.Collections;
public class CellController : MonoBehaviour
{
//get sprite's collider component and assign variable
private CapsuleCollider2D collider2d;
bool isHighlighted = false;
[SerializeField] float movementSpeed = 5f;
Vector3 clickPosition;
// Start is called before the first frame update
void Start()
{
collider2d = GetComponent<CapsuleCollider2D>();
}
IEnumerator Move()
{
while (isHighlighted == true) {
if (Input.GetMouseButtonDown (0)){
// ScreenToWorldPoint
clickPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3 (0, 0, 10f));
// Log location of click
Debug.Log(clickPosition);
float xDistance = Mathf.Abs(clickPosition.x - transform.localPosition.y);
float yDistance = Mathf.Abs(clickPosition.y - transform.localPosition.y);
float moveDistance = (xDistance + yDistance) / 2;
float lerpDuration = moveDistance / movementSpeed;
StartCoroutine(CalculateMove(transform.localPosition, clickPosition, lerpDuration));
}
yield return new WaitForSeconds(0.1f);
}
yield return new WaitForSeconds(0.1f);
}
IEnumerator CalculateMove (Vector3 startPos, Vector3 endPos, float seconds)
{
float t = 0f;
while (t <= 1f) {
t += Time.deltaTime/seconds;
transform.position = Vector3.Lerp(startPos, endPos, Mathf.SmoothStep(0f, 1f, t));
yield return new WaitForSeconds(0.1f);
}
}
// When clicked on, change state
// If highlighted, begin coroutine
void OnMouseDown()
{
isHighlighted = !isHighlighted; // toggle
if (isHighlighted == true){
Debug.Log("Highlighted!");
StartCoroutine("Move");
}
else
{
StopCoroutine("Move");
}
}
}
Comment