0
\$\begingroup\$

I'm trying to implement random enemy movement in a top down shooter game. Currently the enemy moves in a straight line from his current position to a randomly generated target position. Is there any way to make him move in a curved manner using bezier curves or sin wave. Here is the code I have so far.

public float minX;
public float maxX;
public float minY;
public float maxY;
Vector2 targetPosition;
public float speed;

void Start()
{
    targetPosition = GetRandomPosition();
}

void Update()
{       
  if ((Vector2)transform.position != targetPosition)
    {
         transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);            
    }
  else
    {
        targetPosition = GetRandomPosition();            
    }

}

Vector2 GetRandomPosition()
  {
    float randomX = Random.Range(-10, 10);
    float randomY = Random.Range(-10, 10);
    return new Vector2(randomX, randomY);
  }

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.tag == "player")
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Have you tried using Lerp with the actual direction and the direction of your target position? \$\endgroup\$ Sep 15 '21 at 10:23
  • \$\begingroup\$ There are lots of Unity tutorials about working with Bézier splines, and even a built-in function for moving toward a point while maintaining a continuous velocity (Vector2.SmoothDamp). How have you tried implementing this based on your research, and where did you run into a snag applying it to your case? \$\endgroup\$
    – DMGregory
    Sep 15 '21 at 10:33

You must log in to answer this question.

Browse other questions tagged .