Laser Defender. My Projectiles do not destroy the enemy. And I do not know why.
Shooter Code:
[SerializeField] GameObject projectilePrefab;
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float projectileLifetime = 5f;
[SerializeField] float firingRate = 0.2f;
public bool isFiring;
Coroutine firingCoroutine;
void Start()
{
}
void Update()
{
Fire();
}
void Fire()
{
if (isFiring && firingCoroutine == null)
{
firingCoroutine = StartCoroutine(FireContinuously());
}
else if (!isFiring && firingCoroutine != null)
{
StopCoroutine(firingCoroutine);
firingCoroutine = null;
}
}
IEnumerator FireContinuously()
{
while (true)
{
GameObject instance = Instantiate(projectilePrefab,
transform.position,
Quaternion.identity);
Rigidbody2D rb = instance.GetComponent<Rigidbody2D>();
if (rb != null)
{
rb.velocity = transform.up * projectileSpeed;
}
Destroy(instance, projectileLifetime);
yield return new WaitForSeconds(firingRate);
}
}
}
Damage script
{
[SerializeField] int damage = 10;
public int GetDamage()
{
return damage;
}
public void Hit()
{
Destroy(gameObject);
}
}
Player Script
[SerializeField] float moveSpeed = 5f;
Vector2 rawInput;
[SerializeField] float paddingLeft;
[SerializeField] float paddingRight;
[SerializeField] float paddingTop;
[SerializeField] float paddingBottom;
Vector2 minBounds;
Vector2 maxBounds;
Shooter shooter;
void Awake()
{
shooter = GetComponent<Shooter>();
}
void Start()
{
InitBounds();
}
void Update()
{
Move();
}
void InitBounds()
{
Camera mainCamera = Camera.main;
minBounds = mainCamera.ViewportToWorldPoint(new Vector2(0, 0));
maxBounds = mainCamera.ViewportToWorldPoint(new Vector2(1, 1));
}
void Move()
{
Vector2 delta = moveSpeed * Time.deltaTime * rawInput;
Vector2 newPos = new Vector2
{
x = Mathf.Clamp(transform.position.x + delta.x, minBounds.x + paddingLeft, maxBounds.x - paddingRight),
y = Mathf.Clamp(transform.position.y + delta.y, minBounds.y + paddingBottom, maxBounds.y - paddingTop)
};
transform.position = newPos;
}
void OnMove(InputValue value)
{
rawInput = value.Get<Vector2>();
Debug.Log(rawInput);
}
void OnFire(InputValue value)
{
if (shooter != null)
{
shooter.isFiring = value.isPressed;
}
}
}