'Unity 2D NPC teleports instead of moving
I'm new to Unity and C#, but I'm trying to learn by making a basic RPG. I've gotten to a point, where my player character can move, but when I try to make an NPC walk to a specific point, it just teleports instantly.
using UnityEngine;
public class Walker : MonoBehaviour
{
public float walkerSpeed = 1.0f;
public void moveWalker(float x, float y)
{
Vector2 movement = new Vector2(x, y) * walkerSpeed;
movement *= Time.fixedDeltaTime;
transform.Translate(movement);
}
public void ScriptedWalk(float MoveToX, float MoveToY)
{
while (Mathf.Abs(MoveToX - transform.position.x) > 0.05f)
if (MoveToX > transform.position.x)
moveWalker(1, 0);
else
moveWalker(-1, 0);
}
}
I'm calling ScriptedWalk from my NPC's Start function, and I got stuck testing movement on the x axis. The NPC is in X = -2.5 and neds to get to X = 2.
What am I not understanding here?
Solution 1:[1]
Thank you Douglas, as you've suggested in your comment, I used a Coroutine, and changed my ScriptedWalk to this:
public IEnumerator ScriptedWalk(float MoveToX, float MoveToY)
{
if (Mathf.Abs(MoveToX - transform.position.x) < 0.05f)
{
// set animator floats to 0
stopWalker();
}
else
{
// Move east
if (MoveToX > transform.position.x)
moveWalker(1, 0);
// Move west
else
moveWalker(-1, 0);
}
yield return null;
}
I am also calling it from my FixedUpdate method.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PirateNinja |
