Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我怎样才能用一个坐标跟随我的玩家位置移动我的敌人_C#_Unity3d_2d Games - Fatal编程技术网

C# 我怎样才能用一个坐标跟随我的玩家位置移动我的敌人

C# 我怎样才能用一个坐标跟随我的玩家位置移动我的敌人,c#,unity3d,2d-games,C#,Unity3d,2d Games,我正在做一个2d游戏,我想让我的敌人只在Y坐标下跟随我的玩家,这意味着如果我的玩家向上或向下移动,敌人将跟随但不会向前移动。 以下是我当前在敌方脚本中的代码: if (Vector2.Distance(transform.position,target.position) > 200) { transform.position = Vector2.MoveTowards(transform.position, target.posit

我正在做一个2d游戏,我想让我的敌人只在Y坐标下跟随我的玩家,这意味着如果我的玩家向上或向下移动,敌人将跟随但不会向前移动。 以下是我当前在敌方脚本中的代码:

if (Vector2.Distance(transform.position,target.position) > 200)
            {
                transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
            }
else
{
// i want my enemy following my player with only Y coordinate right here, not moving forward anymore
}

Vector2结构有两个位置组件:x和y。要沿y轴移动,请创建临时矢量2以存储变换的位置并仅复制y组件

     Vector2 temporaryPosition = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
     if (Vector2.Distance(transform.position, target.position) > 200)
     {
         //copying the x and y position if the distance is greater than 200
         transform.position = temporaryPosition;
     }
     else
     {
         // copy the x position if the distance is below or equal to 200
         transform.position = new Vector2 (transform.position.x, temporaryPosition.y);
     }
您可以找到更多关于Vector2的文档

     Vector2 temporaryPosition = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
     if (Vector2.Distance(transform.position, target.position) > 200)
     {
         //copying the x and y position if the distance is greater than 200
         transform.position = temporaryPosition;
     }
     else
     {
         // copy the x position if the distance is below or equal to 200
         transform.position = new Vector2 (transform.position.x, temporaryPosition.y);
     }