- Home /
MoveTowards not working
Object will not move towards specified player but instead always to (0,0). Code: public class enemy : MonoBehaviour {
public GameObject player;
public Renderer enemySprite;
void Update()
{
if (enemySprite.isVisible)
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, 9.8f *Time.deltaTime);
}
}
}
be aware that positions in unity are always Vector3s. using a Vector2 $$anonymous$$oveTowards essentially 0s the z value because of the implicit cast of the resulting Vector2 into the necessary Vector3.
@hexagonius i had it working before with vector2 and it only stopped working recently
Answer by sujitmarcus · Dec 04, 2018 at 08:31 AM
https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html
IsVisible will only work if renderer gameobject is in game camera view. Adjust your object you want to move inside your game camera.
i did this on purpose but it still doesnt work when the object is in view
If what @sujitmarcus said isn't the case, you got something else going on that isn't related to this piece of code. I took your code and it works fine, unless of course I move the enemy sprite off screen.
So, what other code is touching this? Or, your player objects visual is a child of a parent that is at zero - and you happened to reference the parent. So the parent is at zero, but the visual is somewhere else.
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Need help with tool animations!! 1 Answer
how to stop rotation from being uncontrollable 1 Answer
Multiple Cars not working 1 Answer