# How to make a character zig-zag while moving towards a moving player

I am working on a 2D shooter and I want one of the types of enemies to spawn and move towards the player while zig-zagging back and forth. The player could be moving, so it needs to dynamically change its direction and the direction of the zig-zagging. It shouldn’t be simply zig-zagging on the x or y axis, but rather side to side relative to the player. How would I do this?

A smarter way is to use the cos function.

``````Vector3 position = new Vector3();
float t = 0f;

void Update {
position.x = AMPLITUDE * Mathf.Cos(t);
position.y += SPEED * Time.deltaTime;

t += Time.deltaTime;
}
``````

you need to derivate the local x axes of your player, or the local y axe…
you do this by calling the transform.right for x axis, or transform.up to y axis

try this:

``````var zigzag :Vector2;
var timer : float;
var player : GameObject;
function Update()
{
timer += Time.deltaTime;
if(timer<0.5)
zigzag = 3*player.transform.right;
if(timer>=0.5&&timer<1)
zigzag = -3*player.transform.right;
if(timer>1)
timer=0;
transform.position += zigzag*Time.deltaTime;

}
``````

or if you need the zigzaging follow the x axis of the enemy, use “transform.right” in the zigzag multiplier.

I was able to do it like this way:

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VirusMove : MonoBehaviour
{

public float speed = 2;
float frequency = 10.0f; // Speed of sine movement
float magnitude = 0.5f; //  Size of sine movement

Vector3 pos;
Vector3 axis;

private void Awake()
{
pos = transform.position;
axis = transform.up;

}

void Update()
{
pos += Vector3.left * Time.deltaTime * speed;
transform.position = pos + axis * Mathf.Sin(Time.time * frequency) * magnitude;
}
``````

for those who want to enable collision use this instead:

``````    pos += Vector3.up * Time.deltaTime * speed;
rb.MovePosition(pos + axis * Mathf.Sin(Time.time * frequency) * magnitude);
``````