【问题标题】:Shoot a Bullet in player direction Unity向玩家方向发射子弹 Unity
【发布时间】:2021-01-26 15:03:41
【问题描述】:

我正在尝试向玩家方向射击子弹,但子弹已安装但未离开初始位置,不知道为什么,代码如下:

using UnityEngine;
using System.Collections;

public class AtackPlayer : MonoBehaviour {
    public string playerTag = "Player";
    public AnimationClip startAtack;
    public AnimationClip endAtack;
    public float atackInterval = 2f;

    public GameObject enemyBullet;
    public float bulletSpeed = 20f;

    private Animator _anim;
    private Transform _transform;

    // Use this for initialization
    void Start () {
        _anim = GetComponentInParent<Animator>();
        _transform = GetComponent<Transform>();
    }
    private IEnumerator Atack(Vector2 playerPosition)
    {
        _anim.Play(startAtack.name);
        yield return new WaitForSeconds(startAtack.length); // executa o clipe e ataca
        GameObject thisBullet = Instantiate(enemyBullet, _transform.position, Quaternion.identity) as GameObject; //instancia o bullet prefab
        thisBullet.transform.position = Vector2.Lerp(thisBullet.transform.position, playerPosition, bulletSpeed * Time.deltaTime);
        _anim.Play(endAtack.name);
        yield return new WaitForSeconds(endAtack.length); // executa o clipe de finalização do ataque
        yield return new WaitForSeconds(atackInterval); // executa o clipe de finalização do ataque
    }
    // Update is called once per frame
    void Update () {


    }
    void OnTriggerEnter2D(Collider2D player)
    {
        if (player.gameObject.tag == playerTag)
        {
            Vector2 playerPos = player.transform.position;
            StartCoroutine(Atack(playerPos));
        }
    }
}

子弹预制件有一个rigidbody2d和一个圆形碰撞器,还有精灵渲染器和一个动画器来处理它的动画。

有什么帮助吗?

【问题讨论】:

  • 也许子弹相信和平、爱和理解。
  • 我要杀了他们=(
  • 我认为是因为您从未告诉它离开初始位置。
  • 初始位置在行中:thisBullet.transform.position = Vector2.Lerp(thisBullet.transform.position, playerPosition, bulletSpeed * Time.deltaTime);

标签: c# unity3d unity5


【解决方案1】:
thisBullet.transform.position = Vector2.Lerp(thisBullet.transform.position, playerPosition, bulletSpeed * Time.deltaTime);

t = bulletSpeed * Time.deltaTime 当 t = 0 时返回 a。当 t = 1 时返回 b。当 t = 0.5 时,返回 a 和 b 之间的中间点。

在你的游戏中,t 的值可能非常接近于 0。这意味着你的 子弹的位置几乎保持不变。你还需要一个 在 Atack 函数中循环以使子弹具有相同的位置 子弹。

while (thisBullet.transform.position != playerPosition)
{    
    thisBullet.transform.position = Vector2.Lerp(thisBullet.transform.position, playerPosition, bulletSpeed * Time.deltaTime);
    yield return new WaitForSeconds(0.1f);
}

您可以在此处根据您的游戏需要设置 while 条件。在这段代码中,它每 0.1f 移动到玩家的位置。

【讨论】:

  • WaitForSeconds 创建一个新对象来启动新的协程,使用 null 代替,这样可以节省一些 GC 调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
相关资源
最近更新 更多