Home>

I'm making a 2D shooting game with unity.
When the enemy hits the bullet, I tried to fly to where I was, but it stopped there.
I want to keep the bullet going on that line.

The following error message occurred while implementing a function.

When an enemy hits a bullet, I try to fly to where I was, but the bullet stops where I was.

Applicable source code

`` `c #
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemybullet: MonoBehaviour
{
GameObject Player;
GameObject Enemy;

public float speed = 3.0f;// movement speed]

public Vector3 PlayerPos {get;private set;}

// Start is called before the first frame update
void Start ()
{
// get player object
this.Player = GameObject.Find ("Player");
this.Enemy = GameObject.Find ("Enemy");

Destroy (gameObject, 3.0f);
// Vector3 PlayerPos = this.Player.transform.position;
PlayerPos = this.Player.transform.position;

}

// Update is called once per frame
void Update ()
{

// float step = speed * Time.deltaTime;
//Enemybullet.transform.position = Vector3.MoveTowards (Enemybullet.transform.position, Player.transform.position, step);

float ENEMY_MOVE_SPEED = 0.05f;

// Move in the direction of the player
transform.position = Vector3.MoveTowards (transform.position, PlayerPos, ENEMY_MOVE_SPEED);

}
}

I think Movetowards is the code that goes there, but what do you use instead?

Supplemental information (FW/tool version etc.)

unity2019.2.19

  • Answer # 1

    I'm a Unity beginner, so I'll connect to the place until a detailed person comes. . .

    Start () calculates "Direction towards player (unit vector)" and stores it in a member variable.
    In Update (), I thought it would be better to transform.Translate (vector created by ↑ * Speed ​​* Time.deltaTime).

  • Answer # 2

    MoveTowards will go to that point, so don't pass

    I think a constant velocity straight bullet looks like this

    Vector3 move;
    void Update () {
      transform.position = transform.position + move * Time.deltaTime;
    }
    // Usage is like this
    // Aim (enmey.transform.positon, player.transform.position, 3.0f);
    void Aim (Vector3 positon, Vector3 target, float speed) {
      move = (target-position) .normalized * speed;
    }

    With STG, Enemy is not just one, and it is always monotonous to aim only at Player, so
    I don't think these values ​​should be retrieved internally