I'm working on enemy AI and I'm trying to make the enemy shoot. However the bullets do not propel forward and I'm not sure how to make it do so. They just appear in front of the enemy and fall rather than move in the direction the enemy faces. The script is currently attached to an empty gameobject in front of the enemy. I'm using this script:
using UnityEngine;
using System.Collections;
///
/// Launch projectile
///
public class WeaponScript : MonoBehaviour
{
//--------------------------------
// 1 - Designer variables
//--------------------------------
///
/// Projectile prefab for shooting
///
public Rigidbody2D shotPrefab;
///
/// Cooldown in seconds between two shots
///
public float shootingRate = 0.25f;
//--------------------------------
// 2 - Cooldown
//--------------------------------
private float shootCooldown;
void Start()
{
shootCooldown = 0f;
}
void Update()
{
if (shootCooldown > 0)
{
shootCooldown -= Time.deltaTime;
}
}
//--------------------------------
// 3 - Shooting from another script
//--------------------------------
///
/// Create a new projectile if possible
///
public void Attack(bool isEnemy)
{
if (CanAttack)
{
shootCooldown = shootingRate;
// Create a new shot
//var shotTransform = Instantiate(shotPrefab) as Transform;
// Assign position
//shotTransform.position = transform.position;
var BulletShot = Instantiate(shotPrefab, transform.position, transform.rotation);
shotPrefab.rigidbody2D.AddForce(transform.forward * 1000);
//shotPrefab.Rigidbody2D.AddForce(transform.forward * 1000);
// The is enemy property
ShotScript shot = shotPrefab.gameObject.GetComponent();
if (shot != null)
{
shot.isEnemyShot = isEnemy;
}
// Make the weapon shot always towards it
MoveScript move = shotPrefab.gameObject.GetComponent();
if (move != null)
{
//move.direction = this.transform.right; // towards in 2D space is the right of the sprite
}
}
}
///
/// Is the weapon ready to create a new projectile?
///
public bool CanAttack
{
get
{
return shootCooldown <= 0f;
}
}
}
↧