如何固定敌人以团结射击球员的方向

发布于 2025-02-03 07:01:08 字数 938 浏览 3 评论 0 原文

我试图让一个法师敌人在射程时用咒语射击。目前,他在正确的时间和正确的距离上拍摄了咒语弹丸,但是由于某种原因,它朝着球员相对于法师的相反方向发射。这是当前的代码。我是团结的新手,因此将不胜感激。

// Variables being used
public float period = 3f;
public GameObject spell;
public GameObject mage;
public GameObject HitBox;
public Transform LaunchOffset;

private float shootingTime;
private Transform playerTransform;


if (Time.time > shootingTime)
{
    shootingTime = Time.time + period;
    Vector3 myPos = new Vector3(LaunchOffset.position.x, LaunchOffset.position.y);
    GameObject projectile = Instantiate(spell, myPos, Quaternion.identity);
    Physics2D.IgnoreCollision(projectile.GetComponent<BoxCollider2D>(), mage.GetComponent<BoxCollider2D>(), HitBox.GetComponent<BoxCollider2D>());
    Vector3 direction = myPos - (Vector3)playerTransform.position;
    projectile.GetComponent<Rigidbody2D>().velocity = direction * spellSpeed;
}

I'm trying to make a mage enemy shoot the player with a spell when he is in range. Currently, he shoots the spell projectile at the right time and at the right distance, but for some reason, it fires in the opposite direction of the player relative to the mage. This is the current code. I'm fairly new to Unity, so any feedback/improvements would be appreciated.

// Variables being used
public float period = 3f;
public GameObject spell;
public GameObject mage;
public GameObject HitBox;
public Transform LaunchOffset;

private float shootingTime;
private Transform playerTransform;


if (Time.time > shootingTime)
{
    shootingTime = Time.time + period;
    Vector3 myPos = new Vector3(LaunchOffset.position.x, LaunchOffset.position.y);
    GameObject projectile = Instantiate(spell, myPos, Quaternion.identity);
    Physics2D.IgnoreCollision(projectile.GetComponent<BoxCollider2D>(), mage.GetComponent<BoxCollider2D>(), HitBox.GetComponent<BoxCollider2D>());
    Vector3 direction = myPos - (Vector3)playerTransform.position;
    projectile.GetComponent<Rigidbody2D>().velocity = direction * spellSpeed;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够钟 2025-02-10 07:01:08

目标点的方向是目标点的位置减去另一个点的位置。因此,只需更改那条代码即可:

Vector3 direction = playerTransform.position - myPos;

以下是更多信息:

Direction of a point towards a target point, is target point's position minus other point's position. So just change that line of code:

Vector3 direction = playerTransform.position - myPos;

Here is more info: https://docs.unity3d.com/2019.3/Documentation/Manual/DirectionDistanceFromOneObjectToAnother.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文