C# 我怎样才能用一个坐标跟随我的玩家位置移动我的敌人
我正在做一个2d游戏,我想让我的敌人只在Y坐标下跟随我的玩家,这意味着如果我的玩家向上或向下移动,敌人将跟随但不会向前移动。 以下是我当前在敌方脚本中的代码: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
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);
}