1
\$\begingroup\$

Basically I'm trying to make enemies attack player and shot bullets towards player and for now is kinda working, but my problem is the bullet stop when it reach the player position instead of keep moving.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyTwoBulletScript : MonoBehaviour {

    public float bulletDamage;

    private float bulletSpeed = 9.5f;
    private float spriteWithDelta;
    //private Rigidbody2D bulletBody;
    private Transform playerTransform;
    private Transform selfTransform;
    private Vector3 playerPosition;


    // Use this for initialization
    void Start() {
        //bulletBody = GetComponent<Rigidbody2D>();
        spriteWithDelta = GetComponent<SpriteRenderer>().bounds.size.x / 2;
        playerTransform = GameObject.FindWithTag("Player").GetComponent<Transform>();
        bulletSpeed = 9.5f;
        playerPosition = playerTransform.position;
        selfTransform = GetComponent<Transform>();


    }
    // Update is called once per frame
    void Update () {
        selfTransform.position = Vector3.MoveTowards(selfTransform.position,playerPosition,bulletSpeed*Time.deltaTime);
    }
}

I don't want the bullet to follow player either, I just want to shot a rect between origin and player, but keep moving when the bullet past player.

\$\endgroup\$
0
\$\begingroup\$

You have to use a direction vector instead of the MoveTowards function. It can be easily done as follow :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyTwoBulletScript : MonoBehaviour {

    public float bulletDamage;

    private float bulletSpeed = 9.5f;
    private float spriteWithDelta;
    //private Rigidbody2D bulletBody;
    private Transform playerTransform;
    private Transform selfTransform;
    private Vector3 playerPosition;
    private Vector3 direction ;


    // Use this for initialization
    void Start() {
        //bulletBody = GetComponent<Rigidbody2D>();
        spriteWithDelta = GetComponent<SpriteRenderer>().bounds.size.x / 2;
        playerTransform = GameObject.FindWithTag("Player").GetComponent<Transform>();
        bulletSpeed = 9.5f;
        playerPosition = playerTransform.position;
        selfTransform = GetComponent<Transform>();
        direction = (playerPosition - selfTransform.position).normalized ;

    }
    // Update is called once per frame
    void Update () {
        selfTransform.position += direction * bulletSpeed * Time.deltaTime;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.