c# - Unity 2D 旋转 AI 敌人看玩家
问题描述
我正在制作一个左右两侧的 2D 游戏,因此玩家只能向左或向右移动或跳跃。我做了一个AI作为敌人。人工智能工作正常。他可以去找玩家杀死他。
问题是当他去杀死他时敌人不能旋转或面对玩家。我想让 AI 看着玩家。当玩家在敌人的左边时,敌人应该旋转到左边看玩家。我搜索了许多网站,但没有得到任何正确的解决方案。这是我的敌人脚本:
public class enemy : MonoBehaviour
{
public float speed;
private Animator animvar;
private Transform target;
public GameObject effect;
public float distance;
private bool movingRight = true;
public Transform groundedDetection;
public float moveInput;
public bool facingRight = true;
void Start()
{
animvar = GetComponent<Animator>();
target = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
void Update()
{
if (Vector3.Distance(target.position, transform.position) < 20)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
else
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
RaycastHit2D groundInfo = Physics2D.Raycast(groundedDetection.position, Vector2.down, distance);
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag.Equals("danger"))
{
Instantiate(effect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
if (col.gameObject.tag.Equals("Player"))
{
Instantiate(effect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
}
游戏是 2D,左,右,使用 Unity3D 跳跃。
解决方案
你需要一个可以翻转你的精灵的函数,你可以通过改变变换的比例来做到这一点,并保持一个布尔值来检查它面对的地方
bool facingRight;
,所以像这样
void Flip(){
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
facingRight = !facingRight;
}
并在您的Update
检查中是否需要翻转
if (Vector3.Distance(target.position,transform.position)<20)
{
transform.position=Vector2.MoveTowards(transform.position, target.position,speed*Time.deltaTime);
if(target.position.x > transform.position.x && !facingRight) //if the target is to the right of enemy and the enemy is not facing right
Flip();
if(target.position.x < transform.position.x && facingRight)
Flip();
}
推荐阅读
- python - 使用 uwsgi 服务器作为 socketio 客户端
- azure - 在 Azure AppServicePlan 上部署 Azure Webjobs 的最佳方式
- react-native - 如何在本地反应中获取社交登录国家/地区?
- .net - 解密.net加密字符串中的Swift问题
- c# - C# Math.Round 不明确的问题
- r - 如何在 R 中操作和存储函数
- linkedin - LinkedIn:如何使用 organizationsEntityShareStatistics 端点检索特定共享的统计信息?
- java - 我的代码是线程安全的吗?如果没有,如何实现线程安全?
- python - pytest-variables:如何在不在测试函数原型中声明变量参数的情况下获取“变量”
- javascript - 如何使用 mocha javascript 在 module.exports 中提供 xpath