简体   繁体   中英

Shoot a Bullet in player direction Unity

I'm trying to shot a bullet in player direction but the bullet is instatiated but dont leave the initial position, not sure why, heres the code:

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));
        }
    }
}

The bullet prefab have a rigidbody2d and a circle collider, also sprite renderer and a animator to handle its animation.

Any help?

thisBullet.transform.position = Vector2.Lerp(thisBullet.transform.position, playerPosition, bulletSpeed * Time.deltaTime);

t = bulletSpeed * Time.deltaTime When t = 0 returns a. When t = 1 returns b. When t = 0.5 returns the point midway between a and b.

In your game probably t has a value very close to 0. It means your bullet's position stays almost the same position. Also you need a loop in Atack function to make bullet has the same position with bullet.

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

You can set while condition here however you want for your game. In this code it move to player's position every 0.1f.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM