unity move units 2d topdown code example
Example 1: how to make 2d top downbenemies in unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour{
public Transform player;
public float moveSpeed = 5f;
private Rigidbody2D rb;
private Vector2 movement;
void Start(){
rb = this.GetComponent<Rigidbody2D>();
}
void Update(){
Vector3 direction = player.position - transform.position;
direction.Normalize();
movement = direction;
}
private void FixedUpdate() {
moveCharacter(movement);
}
void moveCharacter(Vector2 direction){
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
}
}
Example 2: unity movetowards 2d
private void Move(Vector3 target, float movementSpeed)
{
transform.position += (target - transform.position).normalized * movementSpeed * Time.deltaTime;
}