Question by
AngreeCat · Sep 09, 2021 at 11:01 PM ·
scripting problemmovementplayercoroutine
Hit a wall in my RTS movement controller. Issues with MoveToward and Coroutine logic.
So a couple of things off the top. I'm not brand new to programming, but I'm certainly a novice. Most of the code is pulled from examples and modified to my purposes, though because they're from different sources there's definitely room for errors.
The issue at hand is this; my SelectUnit method works fine (as far as I can tell). My MoveToPosition method is not functioning as expected. It simply "teleports" the unit to the coordinates rather than making use of MoveTowards. As well it seems to be throwing a lot of duplicate coordinates to the console, so I'm thinking one of my coroutine loops is not correct.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public static GameObject controlledUnit = null;
private bool unitSelected = false;
private float speed = 1.0f;
private Vector3 moveToPos;
private Vector3 unitPos;
void Start()
{
}
//Coroutines are new to me, so the logic may be wrong here
//MoveToPosition is printing duplicate coordinates to console when it runs (3 the first click, 6 the second click, 9 the third click etc)
IEnumerator UnitController()
{
while (!unitSelected)
{
SelectUnit();
yield return new WaitForSeconds(1);
}
while (unitPos != moveToPos)
{
MoveToPosition();
yield return null;
}
while (unitSelected)
{
DeselectUnit();
yield return null;
}
}
//SelectUnit works fine
void SelectUnit()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) // you can also only accept hits to some layer and put your selectable units in this layer
{
if (hit.collider.tag == "Player")
{
unitPos = gameObject.transform.position;
controlledUnit = hit.transform.gameObject;
unitSelected = true;
Debug.Log("Unit Selected");
}
}
else
{
controlledUnit = null;
}
}
}
//moves player to correct coordinates but is behaving as though transform.position has been directly altered, no MoveTowards functioning
void MoveToPosition()
{
if (unitSelected && Input.GetMouseButtonDown(0))
{
Plane plane = new Plane(Vector3.up, 0);
float distance;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out distance))
{
moveToPos = ray.GetPoint(distance);
moveToPos.y = 1.3f;
Debug.Log(moveToPos);
transform.position = Vector3.MoveTowards(transform.position, moveToPos, speed * Time.deltaTime);
}
}
}
//DeselectUnit works fine
void DeselectUnit()
{
if (unitSelected)
{
unitSelected = !unitSelected;
Debug.Log(unitSelected);
controlledUnit = null;
}
}
void Update()
{
StartCoroutine(UnitController());
}
}
Comment