So I am getting the strangest results with a new enemy bullet and I feel dumb for not knowing why.
It’s a top down shooter, no gravity on the Rigidbody2D.
The intent is so the bullet targets toward the player, then retargets toward the player again every second.
Here is the gruesome result of my script (bullet is weird red bat thing):
https://i.imgur.com/ZQkNozf.mp4
The bullet is jittery, and never goes toward the player. Moving up and down does reveal the bat moves up and down (sort of) as the player does, but it’s so inaccurate it’s barely relevant.
I have debugged the timers and they’re all working correctly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBulletBat : MonoBehaviour
{
public float speed;
public float countdown;
private bool canChangeDirection = false;
private bool canSetVelocity = false;
private Vector3 direction;
private bool playerIsHit;
public GameObject bulletsplosionFX;
private float bulletPiercingPercentage, chancePiercingPercentage;
private Rigidbody2D theRB;
private int countToDestroy = 0;
// Start is called before the first frame update
void Start()
{
countdown = 1f;
playerIsHit = false;
theRB = this.GetComponent<Rigidbody2D>();
bulletPiercingPercentage = ItemTracker.instance.bulletPiercingAmount;
chancePiercingPercentage = Random.Range(0, 99);
}
// Update is called once per frame
void Update()
{
if (countdown > 0)
{
countdown -= Time.deltaTime;
}
else
{
UpdateCountToDestroy();
canChangeDirection = true;
ChangeDirection();
countdown++;
}
//theRB.velocity = direction * speed;
if (playerIsHit)
{
if (!PlayerController.instance.isDodging)
{
HitPlayer();
}
else
{
playerIsHit = false;
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
playerIsHit = true;
}
else if (other.tag == "Player Bullet")
{
if (bulletPiercingPercentage > chancePiercingPercentage)
{
DestroyBullet();
}
}
}
void UpdateCountToDestroy()
{
if(countToDestroy < 6)
{
countToDestroy++;
}
else
{
DestroyBullet();
}
}
void ChangeDirection()
{
if (canChangeDirection)
{
direction = PlayerController.instance.transform.position - transform.position;
direction.Normalize();
canSetVelocity = true;
SetVelocity();
}
canChangeDirection = false;
}
public void SetVelocity()
{
if (canSetVelocity)
{
theRB.velocity = direction * speed;
canSetVelocity = false;
}
}
private void HitPlayer()
{
PlayerHealthController.instance.DamagePlayer();
playerIsHit = false;
DestroyBullet();
}
private void DestroyBullet()
{
Instantiate(bulletsplosionFX, transform.position, transform.rotation);
Destroy(gameObject);
}
private void OnBecameInvisible()
{
DestroyBullet();
}
}
I clearly set this up wrong, but keep rechecking and I’m coming up dry.
Any thoughts? Thanks!