Hello,
So Im working on this simple 2D sidescrolling shooter. I created a script for the player and him shooting on command which works fine.
Next Im trying to get my enemies to shoot bullets at intervals, just to add some difficulty.
I got a script for the enemy shooting and an enemy bullet, it all seems to work fine, except for all the shooting is just flying off to the right?
I really cant figure out what Im missing or doing wrong.
The script for my enemy are:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShooting : MonoBehaviour {
public Transform target; //where we want to shoot(player? mouse?)
public Transform weaponMuzzle; //The empty game object which will be our weapon muzzle to shoot from
public GameObject bullet; //Your set-up prefab
public float fireRate = 3000f; //Fire every 3 seconds
public float shootingPower = 20f; //force of projection
private float shootingTime; //local to store last time we shot so we can make sure its done every 3s
public int health = 100;
public GameObject deathEffect;
private void Update()
{
Fire(); //Constantly fire
}
private void Fire()
{
if (Time.time > shootingTime)
{
shootingTime = Time.time + fireRate / 1000; //set the local var. to current time of shooting
Vector2 myPos = new Vector2(weaponMuzzle.position.x, weaponMuzzle.position.y); //our curr position is where our muzzle points
GameObject projectile = Instantiate(bullet, myPos, Quaternion.identity); //create our bullet
Vector2 direction = myPos - (Vector2)target.position; //get the direction to the target
projectile.GetComponent<Rigidbody2D>().velocity = direction * shootingPower; //shoot the bullet
}
}
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
void Die()
{
Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
Then I got a script for the bullet itself which is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bulletenemy : MonoBehaviour {
public float speedshooting = 20f;
public int damage = 40;
public Rigidbody2D rb;
public GameObject impactEffect2;
// Use this for initialization
void Start () {
rb.velocity = transform.right * speedshooting;
}
private void OnTriggerEnter2D(Collider2D HitInfo)
{
Enemy enemy = HitInfo.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
Instantiate(impactEffect2, transform.position, transform.rotation);
Debug.Log(HitInfo.name);
Destroy(gameObject);
}
}
How do I get them to shoot off to left with this?
All the best