- Home /
Object Not Moving - Yield - IEnumerator
Hope everyone's doing amazing.
I want to move an object to the position of the mouse when I click.
Here's what happens, I've attached this script to the point of origin(player) using that point to create the object and calls for a function called getDestination.
void Update ()
{
if(Input.GetMouseButtonDown(1))
{
playerPosition = player.transform.position;
//Get users input position(where they shoot);
userInputPosition = (new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
userInputPosition = Camera.main.ScreenToWorldPoint(userInputPosition);
Debug.Log ("User clicked here:" + userInputPosition);
Debug.Log ("Here's The player:" + playerPosition);
projectile = ObjectPoolManager.CreatePooled( object2Spawn, transform.position, player.transform.rotation ).GetComponent<bulletActions>();
//Test to move the projectile.
projectile.GetComponent<bulletActions>().getDestination(userInputPosition);
}
}
Get destination gets the point where the user clicked and the idea is that the object created moves smoothly towards that point, once the point is reached. Destroy the object.
void OnTriggerEnter (Collider other) {
Debug.Log ("OnTrigger");
Debug.Log (collider.gameObject.name);
EliminateThisObject ();
Destroy (other.gameObject);
}
public void getDestination (Vector3 destination)
{
Debug.Log ("Destination is :" + destination);
Debug.Log ("Position is" + transform.position);
projectileDestination = destination;
gotDestination = true;
moveToDestination ();
}
private IEnumerator moveToDestination ()
{
while (gotDestination == true)
{
transform.position = Vector3.Lerp(transform.position, projectileDestination, moveSpeed * Time.deltaTime);
Debug.Log ("mtd Destination is :" + projectileDestination);
Debug.Log ("mtd Position is" + transform.position);
if(transform.position == projectileDestination)
{
EliminateThisObject();
gotDestination = false;
Debug.Log ("Update, position is the same as destination");
}
yield return null;
}
}
I've added a couple of Debugs with mtd on it to test if the method is happening "(IEnumerator moveToDestination)" but its not appearing. Am I doing the best way to accomplish this situation?
Thanks for your help and time!
Answer by supernat · Mar 10, 2014 at 09:59 PM
A couple of things you'll want to do. Use StartCoroutine() to start the moveToDestination, and place an if statement around the call to make sure it doesn't happen multiple times, like this:
if (!getDestination)
{
getDestination = true;
StartCoroutine(moveToDestination());
}
Let me know if that doesn't do what you're looking to do. Basically, the StartCoroutine will run your moveToDestination method in small time slices (each yield call), but without it, I'm not sure what behavior to expect.
Thanks, I looked it up and just like you said!! Thank you man!