Search code examples
c#unity-game-enginegame-physics

How to improve targeting of enemy where the player stays stationary while everything else moves?


I'm making an infinite runner game, using an infinite runner engine, which works by making the player/runner stay at its same position while the background elements, platforms and enemies come at the player.

This was working fine until I introduced enemy shooting, where the enemies locate and shoot the player. I'm using the following script that is on the EnemyBullet prefab:

void Start()
    {


        shooter = GameObject.FindObjectOfType<Player>();
        shooterPosition = shooter.transform.position;
        direction = (shooterPosition - transform.position).normalized;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position += direction * speed * Time.deltaTime;
    }

This works, but the problem is that it is way too accurate, like even when the player is jumping the bullet prefab tends to guess its position and is shot directly at the player.

I know this is because the player does not actually move and this makes the targeting of the player very easy.

Is there any way to improve this? Or in a way make it more natural?

Thanks


Solution

  • The problem is that in the code

    shooter = GameObject.FindObjectOfType<Player>();
    shooterPosition = shooter.transform.position;
    direction = (shooterPosition - transform.position).normalized;
    

    Since shooter.transform.position is the player's location and transform.position is the bullet's location, then shooterPosition - transform.position is giving you a vector that points directly from the bullet's location to the player's location.

    It sounds like what you want to do is add some amount of inaccuracy to the bullet (correct me if I'm wrong). You could use something like this to do that (I'm assuming this is 2D?)

    shooter = GameObject.FindObjectOfType<Player>();
    shooterPosition = shooter.transform.position;
    direction = (shooterPosition - transform.position).normalized;
    
    // Choose a random angle between 0 and maxJitter and rotate the vector that points 
    // from the bullet to the player around the z-axis by that amount.  That will add
    // a random amount of inaccuracy to the bullet, within limits given by maxJitter
    var rotation = Quaternion.Euler(0, 0, Random.Range(-maxJitter, maxJitter));
    direction = (rotation * direction).normalized;